简体   繁体   中英

Angular 2+ and subjects

I found angular subject simple example in the internet. I try to use code from example, using subject but i don't getting any result for workTime variable. Where's the problem?

Work.service.ts

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

Few modifications in your code, please check

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; });
  }
}

The AppComponent emits the value before BossComponent has the chance to subscribe. If you want the Subject to replay the last emited value to new subscribers use ReplaySubject .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM