在 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$
. 另一方面,当我做 place 时this.data$.subscribe();
,控制台得到正确的输出,但视图仍然是空的(挂在Loading...上)。
谁能解释发生了什么?