如何解决Angular @Input在浏览器上不起作用并且组件无法渲染
// ...
ngOnInit() {
this.products$.subscribe(products => {
this.products = products;
})
}
// ...
<!-- ... -->
<ng-container *ngIf="products">
<product-list [products]="products"></product-list>
</ng-container>
<!-- ... -->
在孩子product-list
上:
// ...
@input() products: IProduct[];
// ...
<!-- ... -->
<div *ngFor="let product of products">
<product-card [product]="product">
</div>
<!-- ... -->
然后,每个product-card
节目都显示product.image
。
我面临的问题是,每当我进入该页面时,我都可以查看所有产品,但是当我单击页面上的某些内容而不是浏览器返回此页面时,产品列表为不显示。
我在控制台中没有任何错误,我可以确认子组件正在第二个渲染器上接收数据,并在调试控制台中添加了调试点。
为什么我的子组件仅在第一个渲染器上显示?甚至刷新都行不通。 仅当我通过在浏览器中输入URL导航到页面时,我才会显示相同的组件。预先感谢。
解决方法
ngInit不会在导航返回时被调用。使用ActivatedRoute并订阅参数:
constructor(route: ActivatedRoute) {
route.params.subscribe(x => {
});
}
如果要同时订阅两者,请使用CombineLatest。 https://www.learnrxjs.io/learn-rxjs/operators/combination/combinelatest
,结果是,我的顶级组件未实现OnDestroy
,并且该组件在重定向后仍然存在。我通过以下操作解决了这个问题:
@Component({ /* ... */ })
class topComponent implements OnInit,OnDestroy {
// ...
private readonly destroy$ = new Subject<void>();
// ...
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
}
destroy$.[METHOD]
将释放您使用this.[SELECT].pipe(takeUntil(this.destroy$)).subscribe(...)
所订阅的所有可观察的观测值。很整齐。
感谢您的所有帮助!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。