Angular2-* ngIf和异步可观察对象 [英] Angular2 - *ngIf and async observables
本文介绍了Angular2-* ngIf和异步可观察对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将* ngIf与可观察变量一起使用时遇到问题.问题是,当我用 * ngIf 隐藏元素并再次显示它时,值将不会加载:
I have problem with using *ngIf with observable variables. The thing is that when I hide element with *ngIf, and show it again, values won't load so:
<div *ngIf="showDiv">
{{ someObservable$ | async }}
</div>
基本上,当首先将showDiv设置为 true 时,就会加载someObservable,但是当我将其设置为 false 时,又再次将其设置为 true strong>,将不会加载值.怎么了?
Basically when showDiv is set to true at the first place, the someObservable loads, but when I set it to false and then again to true , value won't load. What's wrong?
致谢
推荐答案
更新:
感谢j2L4e的提示!
Thanks to j2L4e, for his hint!
BehaviorSubject
是关键!
看到这个矮人:
https://plnkr.co/edit/whkrQk3tHCJCvvi6rlaE?p=info
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { Subject, BehaviorSubject } 'rxjs/Rx';
//import { Observable, Subject } from 'rxjs';
@Component({
selector: 'my-app',
template: `
<div>
<h2 (click)="showMe = !showMe">Hello {{name}}</h2>
<br />
<div *ngIf="showMe">
sbj1: {{ _subj1 | async }}
</div>
<div *ngIf="showMe">
obs1: {{ _obs1 | async }}
</div>
<div *ngIf="showMe">
obs2: {{ _obs2 | async }}
</div>
</div>
`,
})
export class App {
private showMe = false;
private _subj1 = new BehaviorSubject<string>();
private _subj2 = new Subject<string>();
private _obs1 = this._subj1.asObservable();
private _obs2 = this._subj2.asObservable();
constructor() {
this.name = 'Angular2'
this._subj1.next('in constructor');
}
ngAfterViewInit() {
this._subj2.next('after view init..');
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
这篇关于Angular2-* ngIf和异步可观察对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文