簡體   English   中英

Angular 2+和主題

[英]Angular 2+ and subjects

我在互聯網上找到了角度主題的簡單例子。 我嘗試使用示例中的代碼,但使用subject,但是workTime變量沒有任何結果。 哪里出問題了?

工作服務

import { Subject } from "rxjs/Subject";
import "rxjs/Rx";

@Injectable()
export class WorkService {

  public $workTimeSubject: Subject<number> = new Subject();

  constructor() { }
}

app.component.ts:

export class AppComponent implements OnInit{

  constructor(private _workService: WorkService) { }

  ngOnInit() {
    this._workService.$workTimeSubject.next(40);
    console.log('app init');

    this._workService.setWorkTime(40);
  }
}

Boss.component.ts:

export class BossComponent implements OnInit {

  workTime: number;

  constructor(private _workService: WorkService) { }

  ngOnInit() {
    this._workService.$workTimeSubject.subscribe((value) => {
      this.workTime = value;
      console.log('value', value);
    });
  }
}

boss.component.ts

{{ workTime }}

您的代碼修改很少,請檢查

Work.service.ts:

import { Subject } from "rxjs/Subject";
import "rxjs/Rx";

@Injectable()
export class WorkService {

  private $workTimeSubject: Subject<number> = new Subject();

  updateWorkTime(time: number) {
    this.$workTimeSubject.next(time);
  }

  getWorkTime(): Observable<any> {
    return this.$workTimeSubject.asObservable();
  }
}

app.component.ts:

export class AppComponent implements OnInit{

  constructor(private _workService: WorkService) { }

  ngOnInit() {
    this._workService.updateWorkTime(40);
    console.log('app init');
  }
}

Boss.component.ts:

export class BossComponent implements OnInit {

  workTime: number;
  subscription: Subscription;

  constructor(private _workService: WorkService) {
    this.subscription = this._workService.getWorkTime().subscribe(time => { this.workTime = time; });
  }
}

BossComponent有機會訂閱之前, AppComponent會發出該值。 如果要讓Subject向新訂閱者重播上一次發出的值,請使用ReplaySubject

替換: public $workTimeSubject: Subject<number> = new Subject();

使用: public $workTimeSubject: ReplaySubject<number> = new ReplaySubject(1);

暫無
暫無

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

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