【发布时间】:2021-08-23 01:17:51
【问题描述】:
我的代码从 Application State 获取数据,然后在 component.html 中显示数据。
component.ts
myData$: Observable<IMyData>;
ngOnInit() {
this.myData$ = this.myStore.select(fetchMyData);
// here I get a code and I use it to dispatch a new action
this.myStore.select(codeSelector).pipe(
map((code) => this.myStore.dispatch(myDataAction({ code: code })))
).subscribe();
}
component.html
{{myData$.myField}}
上面的代码完美运行。
现在,我不想在 component.ts 中调用 subscribe() 方法,而是在 component.htmlasync 管道/strong>,这样:
<ng-container *ngIf="myData$ | async as data">
{{data.myField}}
当我这样做时,component.html 中不会显示任何内容。我知道在我后面的代码中,我使用的运算符有问题。
我多次使用异步管道,但仅在调度标准操作时使用;在操作员内部调度操作时,我从未使用过它。
你能帮我理解我的错误吗?
【问题讨论】:
-
在地图运算符内部,您返回的是操作而不是可观察的 map((code) => this.myStore.dispatch(myDataAction({ code: code })))
-
嗨@Chellappanவ,我应该如何编辑我的代码?
-
您的
subscribe()正在订阅this.myStore.select(codeSelector)。没有它,您的商店选择器将不会返回任何内容,因为它是冷可观察的。作为回报,它不会执行您的操作,并且可能不会更新fetchMyData正在选择的您的商店数据。顺便说一句,正如一个答案所暗示的,您应该使用tap()而不是map() -
嗨@FrankFajardo,谢谢你的解释。现在我知道我必须订阅“this.myStore.select(codeSelector)”才能使“this.myData$ = this.myStore.select(fetchMyData)”工作;然后我可以在模板内的“myData$”上使用异步管道。
标签: angular redux rxjs store application-state