繁体   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