簡體   English   中英

Angular2 - *ngIf 和異步可觀察對象

[英]Angular2 - *ngIf and async observables

我在將 *ngIf 與可觀察變量一起使用時遇到問題。 問題是,當我用*ngIf隱藏元素並再次顯示時,值不會加載,因此:

        <div *ngIf="showDiv">
             {{ someObservable$ | async }}
        </div>

基本上,當 showDiv 首先設置為true時, someObservable 會加載,但是當我將其設置為false然后再次設置為true 時,不會加載值。 怎么了?

問候

更新:

感謝 j2L4e 的提示!

BehaviorSubject是關鍵!

看到這個plunker:

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 {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM