[英]How to reuse observable list within component Angular 6
I want to reuse observable list, trying following but not working:我想重用可观察列表,尝试以下但不起作用:
this.transactions is a observable list this.transactions是一个可观察的列表
this.transactions.pipe(
map(actions => actions.map(t => {
if (t.type === 1) {
} else if (t.type === 2) {
}
}
}))
);
Object view:对象视图:
It's nothing happen, no looping no mapping, Please help.什么也没有发生,没有循环没有映射,请帮忙。
The map operator returns a new observable, you need to assign the new observable to a property. map 操作符返回一个新的 observable,您需要将新的 observable 分配给一个属性。
transactions$ = this.someService.transactions$;
mappedTransactions$ = this.transactions$.pipe(map(yourMapFunction));
Now you have an observable that you can either subscribe to or use in the template with the async pipe.现在你有了一个 observable,你可以通过异步管道订阅或在模板中使用它。 Nothing happens until a subscription happens.
在订阅发生之前什么都不会发生。
It is a common pitfall with RXJS for one to not subscribe to their observables. RXJS 的一个常见陷阱是不订阅他们的 observable。 In angular there are two common ways to achieve this.
在 angular 中有两种常见的方法来实现这一点。
Async - In the HTML.异步 - 在 HTML 中。 They ASYNC pipe will subscribe and unsubscribe for you.
他们的 ASYNC 管道将为您订阅和取消订阅。 Additionally the "as" syntax creates a scoped variable that contains the content that your observable emits.
此外,“as”语法创建了一个作用域变量,其中包含您的 observable 发出的内容。
<ng-container *ngIf="transactions$ | async as transactions">
... interact with your observable data
</ng-container>
Subscribe/Unsubscribe - In your code.订阅/取消订阅 - 在您的代码中。 Add a subscribe call to your observables to have them emit.
向您的 observable 添加订阅调用以让它们发出。 Side effect - You have to unsubscribe to prevent memory leaks.
副作用 - 您必须取消订阅以防止内存泄漏。
ngOnInit():void {
this.tSub = this.someService.transactions$
.subscribe(successHandler, errorHandler, completeHandler);
}
ngOnDestroy():void {
this.tSub.unsubscribe()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.