Angular 角度2+;及科目

Angular 角度2+;及科目,angular,rxjs,Angular,Rxjs,我在网上找到了一个简单的例子。我尝试使用示例中的代码,使用subject,但对于workTime变量我并没有得到任何结果。问题出在哪里 工作服务 import { Subject } from "rxjs/Subject"; import "rxjs/Rx"; @Injectable() export class WorkService { public $workTimeSubject: Subject<number> = new Subject(); constru

我在网上找到了一个简单的例子。我尝试使用示例中的代码,使用subject,但对于workTime变量我并没有得到任何结果。问题出在哪里

工作服务

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

@Injectable()
export class WorkService {

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

  constructor() { }
}
Boss.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);
  }
}
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 }}

AppComponent
BossComponent
有机会订阅之前发出值。如果希望主题向新订阅者重播上次发出的值,请使用
ReplaySubject

替换:
public$workTimeSubject:Subject=newsubject()

与:
public$workTimeSubject:ReplaySubject=newReplaySubject(1)

代码中的一些修改,请检查

工作。服务。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();
  }
}
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的子级,它的作用是
console.log('value',value)打印?它什么也不打印,我的意思是,甚至“值”也不打印。我认为您应该使用行为主题,因为它将始终存储以前的值。因此,即使您在设置值后订阅,您也会得到值。问题是,我在ngOnInit中使用subscribtion设置函数,而不是构造函数。您应该在ngOnInit中设置它。构造函数应用于依赖项注入。请查看我的答案。但是在boss.component的构造函数中的订阅会怎么样呢?
export class BossComponent implements OnInit {

  workTime: number;
  subscription: Subscription;

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