由于服务构造函数在组件之前出现,因此crmService.actualName.subscribe()
直到下一次发出时才发生。
加入新订阅时,有什么方法可以发出权利?这样我可以用当前值“回复” ...
像这样的东西:
this.actualName.onSubscribe(x => emit(x));
https://stackblitz.com/edit/angular-ns7j2n?file=src%2Fapp%2Fapp.component.ts
@Injectable({ providedIn: "root"})
export class CrmService {
public actualName : EventEmitter<string> = new EventEmitter();
constructor(){
this.actualName.emit("Angular 6 is the actual name")
}
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
})
export class AppComponent {
name = 'Angular';
constructor(private crmService : CrmService){
crmService.actualName.subscribe(name => {
this.name = name;
});
}
}
答案 0 :(得分:0)
使用BehaviorSubject
代替EventEmitter
。将您的服务代码更改为以下内容:
import { Component, Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({ providedIn: "root"})
export class CrmService {
public actualName : BehaviorSubject<string> = new BehaviorSubject('');
constructor(){
this.actualName.next("Angular 6 is the actual name")
}
}
链接到working demo。