我刚开始使用angular 8,在我的项目中。
我的html元素尝试显示仍未加载的数据。 这是HTML:
<tr *ngFor="let p of products; let i = index;">
<td width="">{{productType(p.productTypeId)}}</td>
</tr>
productType是一个返回值以从组件显示的函数。
这是productType函数的定义:
productType(id){
return this.productTypes.find(x => x.id === id).text;
}
这是我加载资源的方式:
ngOnInit() {
this.productTypeService.getAll().subscribe(data => {
this.productTypes = data;
});
this.productService.getAll().subscribe(data => {
this.products = data;
});
}
但是似乎在触发productType时,productTypes资源仍然没有加载。
所以我的问题有什么办法可以解决该错误?
答案 0 :(得分:0)
这不是错误,只是处理异步数据的问题。您所能做的就是仅在this.productTypes
使用ngIf
指令获得数据后才呈现数据。
<ng-container *ngIf="this.productTypes">
<tr *ngFor="let p of products; let i = index;">
<td width="">{{productType(p.productTypeId)}}</td>
</tr>
</ng-container>
有关ngIf的更多信息
替代
将两个数据流组合成一个可观察的
ngOnInit(){
combineLatest([
this.productService.getAll(),
this.productTypeService.getAll()]
)
.pipe(
map(([products, productTypes]) = > {
return products.map((product) =>
({
...product,
productType: productTypes.find(product => product.id === id).text
})
)
})
)
.subscribe(data => {
this.products = data;
});
}
然后您的html如下所示:
<tr *ngFor="let p of products; let i = index;">
<td width="">{{p.productType}}</td>
</tr>
在combineLatest上阅读
您可以全力以赴,不订阅,但可以使用模板中的async
管道。 async pipe
答案 1 :(得分:0)
我想您需要尝试使用awk '
{
# Total Counter
nn++ ;
# Group id
gsize = 1000
gid = int(($1-1)/gsize )
v = $2
# Setup new group, if needed
if ( !n[gid] ) {
n[gid] = 0
sum[gid] = 0
max[gid] = min[gid] = v
name[gid] = (gid*gsize +1) "-" ((gid+1)*gsize)
}
if ( v > max[gid] ) max[gid] = v
sum[gid] += v
n[gid]++
}
END {
# Print all groups
for (gid in name) {
printf "%-20s %4d %6.1f %5.1F\n", name[gid], max[gid], sum[gid]/n[gid], n[gid]/nn ;
}
}
'
进行请求才能及时获取数据
您需要像这样从rxjs导入它
forkJoin
import { forkJoin } from 'rxjs/internal/observable/forkJoin';
这是您想要的吗?