如果我需要在我的组件模板中绑定(bind)来自同一个可观察对象的多个属性......
例如:
<my-random-component[id]="(myObservable$ | async).id">
...
<my-random-component2[name]="(myObservable$ | async).name">
...我最好像上面那样做(我看到很多),还是在我的 .ts 文件中订阅我的可观察对象,设置单个对象变量,然后绑定(bind)到它更有效?后一种方法的想法是 observable 只会被调用一次。
问题:
谢谢!
最佳答案
使用异步管道可以更轻松地处理订阅。与组件中的订阅不同,它会自动处理取消订阅。
也就是说,有一个比示例显示的更好的模式。您可以用两种不同的方式编写它,而不是对组件进行多次异步调用。我假设这些组件在同一个模板文件中:
<div *ngIf="(myObservable$ | async) as myObservable">
<my-random-component [id]="myObservable.id">
<my-random-component2 [name]="myObservable.name">
</div>
将代码包装在 ngIf
中做两件事:myObservable$
之前不存在准备好了如果您想坚持每次都调用 async,还有一个想法:
// COMPONENT
name$: Observable<string>;
id$: Observable<string>;
ngOnInit() {
// Return the exact value you want rather than the full object
this.name$ = OBSERVABLE_SOURCE
.pipe(
map(res => res.name)
);
this.id$ = OBSERVABLE_SOURCE
.pipe(
map(res => res.id)
);
}
// TEMPLATE
<my-random-component [id]="(id$ | async)">
<my-random-component2 [name]="(name$ | async)">
没有订阅,管道不会自动运行。你可以用它来映射、点击或做任何你想做的事情,在你添加 async/.subscribe()
之前它不会运行。 .
关于Angular - 在模板中多次使用异步管道时可观察到......好的做法还是坏的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52749640/