简体   繁体   English

如何将 BehaviorSubject 与 Observable 一起使用

[英]how to use BehaviorSubject with Observable

I have a div and need to add attribute depends on store result.我有一个 div,需要添加属性取决于商店结果。 The store works as expected, when I click on certain div it's value changed (return true or false ) and in my component I need to get updated value, but as I call it in ngOnInit it works only once and not updating.商店按预期工作,当我单击某个 div 时,它的值发生了变化(返回truefalse ),并且在我的组件中我需要获取更新的值,但是当我在ngOnInit中调用它时,它只工作一次而不更新。 I've read about BehaviorSubject but don't understand how to convert my observable to it correctly.我已经阅读了有关BehaviorSubject的信息,但不明白如何正确地将我的 observable 转换为它。 Would appreciate any help!将不胜感激任何帮助!

Here's my code这是我的代码

html html

<div class="details__header" [attr.isOpened]="isOpened ? 'opened' : 'closed'">

ts ts

isOpened: boolean;

constructor(private store: Store<AppState>) { }

ngOnInit(): void {
  this.store.select(selectSearchResultState).subscribe(el => this.isOpened = el);
}

I've tried async pipe in html and it works, but I need to use this variable in my code, so this doesn't work for me我已经在 html 中尝试了async pipe 并且它可以工作,但是我需要在我的代码中使用这个变量,所以这对我不起作用

You should define isOpened as an Observable like this:您应该像这样将isOpened定义为 Observable:

isOpened$: Observable<boolean>;

constructor(private store: Store<AppState>) { }

ngOnInit(): void {
  this.isOpened$ = this.store.select(selectSearchResultState);
}

Then use it in the template with an async pipe:然后在带有异步 pipe 的模板中使用它:

<div class="details__header" [attr.isOpened]="(isOpened$ | async) ? 'opened' : 'closed'">

There's more information about observables in the documentation here .此处的文档中有更多关于 observables 的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM