我们正在尝试将数据从一个组件传递到另一个组件,下面是我们采用的方法。当没有数据时,我们要显示错误消息
<div *ngIf="showGlobalError">
<h6>The reporting project doesn't have any Shippable Items</h6>
</div>
和component.ts就像
showGlobalError = true;
constructor(private psService: ProjectShipmentService, private pdComp: ProjectDetailsComponent) {
this.psService.tDate.subscribe(x => this.cachedResults = x);
}
ngOnInit() { }
ngDoCheck() {
if (this.cachedResults.length > 0 && this.count <= 1) {
this.showGlobalError = false;
this.populateArrays();
this.count++;
}
}
populateArrays() {
this.reportingProject = [this.pdComp.rProjectNumber];
this.projectSalesOrder = this.pdComp.rSalesOrder;
this.clearFilter();
........
问题是,即使this.cachedResults中的数据为this.cachedResults.length几秒钟不等于“ 0”,页面中仍显示“报告项目没有任何可运输的物品”,并且然后显示数据,我不确定ngDoCheck()是否会引起这种情况。任何帮助将不胜感激
答案 0 :(得分:0)
由于showGlobalError
的默认值为true,因此页面加载会显示错误消息。
请默认将其设为false,并在this.cachedResults.length
为0
或this.cachedResults
为undefined
或this.cachedResults
为null
时使其为true。
希望这可以解决您的问题。
答案 1 :(得分:0)
您可以在模板中使用异步管道,而不是订阅代码
items$ = this.psService.tDate;
showGlobalError$ = this.items$.pipe(map(results => !results || !results.length));
constructor(private psService: ProjectShipmentService, private pdComp: ProjectDetailsComponent) { }
并在您的模板中
<div *ngIf="showGlobalError$ | async">
<h6>The reporting project doesn't have any Shippable Items</h6>
</div>
<ng-template *ngFor="let item of items$ | async">
Do stuff with {{item | json}}
</ng-template>
这将为您管理订阅,并通过不取消订阅的方式解决代码中的内存泄漏。
看看我为此类事情编写的图书馆,这使缓存数据变得容易得多。 https://medium.com/@adrianbrand/angular-state-management-with-rxcache-468a865fc3fb