在 Angular (v12) 中,我有以下组件(使用虚拟变量名称):
export class DataDetailsComponent {
data$: Observable<MyDataModel>;
constructor(dataService: DataService, route: ActivatedRoute, private router: Router) {
this.data$ =
combineLatest([dataService.getDataObservable(), router.events])
.pipe(
filter(([,event]) => event instanceof ActivationEnd),
tap(([data, event]) => console.log((<ActivationEnd>event).snapshot.queryParams['id'])),
map(([data, event]) => data.filter(c => c.id === (<ActivationEnd>event).snapshot.queryParams['id'])[0]),
tap(dataItem => console.log(dataItem))
);
this.data$.subscribe(); // console.logs don't work without this
}
}
及其模板:
<div *ngIf="data$ | async as data; else loading">
<img [src]="data.url" [alt]="data.name">
</div>
<ng-template #loading>Loading...</ng-template>
数据没有被渲染,如果我没有真正订阅 data$
,浏览器控制台是空的。另一方面,当我放置 this.data$.subscribe();
时,控制台会得到正确的输出,但视图仍然是空的(挂在 Loading... 上)。
谁能解释一下这是怎么回事?
答案 0 :(得分:0)
可以与您的 combineLatest 相关。检查以查看两个 observable 都在发出数据。
组合最新定义:
<块引用>注意 combineLatest 不会发出初始值,直到每个 observable 至少发出一个值。这是相同的行为 withLatestFrom 并且可能是一个陷阱,因为没有输出也没有 错误,但您的一个(或多个)内在可观察对象可能不是 按预期运行,或者订阅延迟。
你可以使用 startWith 操作符来为 observable 设置一些初始值。
答案 1 :(得分:0)
最后,是路由器事件没有让 observable 完成。
显然,如果我将导航从模板移动到 .ts 并订阅 ActivatedRoute.params
而不是 Router.events
,它会起作用。
所以,父组件得到:
navigateToDetails(id: string): void {
this.router.navigate(['/myRoute', id]);
}
而不是在模板中使用 routerLink
:
<a [routerLink]="['/myRoute']" [queryParams]="{id: item.id}">
然后,在 DataDetailsComponent
我可以:
constructor(dataService: DataService, route: ActivatedRoute) {
this.data$ =
combineLatest([dataService.getDataObservable(), route.params])
.pipe(map(([data, params]) => data.filter(c => c.id === params['id'])[0]));
}
我现在无法理解的原因。