我正在尝试使用不同的param路由到同一个组件,该param会更改通过异步管道在模板中订阅的Observable。几乎与本书一样:https://angular.io/guide/router#activated-route-in-action,但是当paramMap发出新值时我改变了Observable,但不知何时检测到变化或检测没有发生。
Angular v.4.3.6
模板:
<div *ngIf="game$ | async as game" class="card">
组件:
game$: Observable<AdminGame>;
constructor(
private route: ActivatedRoute,
private router: Router,
....) {}
ngOnInit(): void {
this.game$ = this.route.paramMap
.switchMap((params: ParamMap) => {
let id = params.get('id') || '';
if (id === 'newGame') {
return Observable.of({} as AdminGame);
}
return this.adminService.getGame(id);
});
}
最初我访问组件为“/ adminGame / newGame”绑定Observable.of({} as AdminGame)
然后在其中我获得新ID并导航到“/ adminGame / id-of-new-game”:
this.router.navigate(['/adminGame',id]);
应绑定到this.adminService.getGame(id)
的结果。
虽然我可以看到服务中的数据通过,但async没有检测到任何变化。
如果我在其他地方路线然后转到['/adminGame',id]
在其他类似的主题上有对 out of ngZone 的引用,但我认为我的服务只是Angular中的通用http Injectable服务。
修改
如果我在导航更改之前执行相同的操作,它甚至可以工作:
this.game$ = this.adminService.getGame(id);
this.router.navigate(['/adminGame',id]);
为什么异步没有检测到switchMap中的变化?