问题描述
ngOnInit() 中有 Observable。
ngOnInit() {
this.products$ = this.someService.getMissingProducts();
}
this.products$ 是 Observable
抱歉这个愚蠢的问题。我不擅长打字稿和角度,所以我试图找到一些解决方案但失败了。
有什么简单的方法吗?
提前致谢。
this.products$ = this.someService.getMissingProducts().pipe(
map( product => {
return product;
}),map((array:Product[]) => {
return array.map((item:Product) => {
blabla~
return { ...item};
});
})
);
解决方法
import { Subscription } from 'rxjs';
subscription: Subscription;
ngOnInit() {
this.products$ = this.someService.getMissingProducts();
this.subscription = this.products$.subscribe((res: any) => {
this.something = res;
})
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
一些注意事项: 这是为打字稿文件所做的实现。 要从 observable 中获取值,我们必须订阅它。 当我们订阅时,我们会存储订阅并在销毁时取消订阅(否则会导致应用程序内存泄漏)。
还有异步管道,以防您想直接在 HTML 模板中使用 observable:https://angular.io/api/common/AsyncPipe 例如,如果您的 observable 将输出一个字符串,我们可以像这样使用它(使用您示例中的代码):
<span>Observable value is {{ productName$ | async }}</span>
在可能的情况下使用模板中的 observable 会更好,因此我们不需要存储 observable 订阅,并记住销毁它以防止内存泄漏。 取消订阅将通过使用异步管道从 Angular 自动处理。
,使用 rxjs map
运算符将可观察的值从一个转换为另一个。 Link;
ngOnInit() {
this.products$ = this.someService.getMissingProducts().pipe(
map( payload => {
// Perform the operations you want.
return NewValue;
}
);
}
通过 pipe
运算符,您可以使用 map
运算符应用自定义逻辑将 observable 的值更改为其他值。想要。
假设您在 HTML 模板中使用 async
订阅,则不需要在类中订阅。如果您没有在模板中使用异步管道,请务必在 OnDestroy