[英]Angular 2+: data binding using Subjects is not working in ngOnInit
[英]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.