至少有两种方法可以解决这个问题,但希望这能给你一个开始。接受反馈和纠正。
使用可观察的
让服务拥有价值更改的知识并发出更改。组件侦听
上的事件发射器
1.
Creating and returning Observable from Angular 2 Service
)
MyAppService
import { Subject } from 'rxjs/Subject';
@Injectable()
export class MyAppService {
private valueSource = new Subject<any>();
public valueUpdate$ = this.valueSource.asObservable();
putValue(payload: JSON){
return this.apiClientService.putAPIObject(payload).then((response) => {
/** here **/
this.valueUpdate$.next(response);
});
}
}
MyAppComponent
export class MyAppComponent {
public value;
private valueSubscription;
constructor(private _myAppService: MyAppService) {}
ngOnInit() {
/** and here **/
this._myAppService.valueUpdate$.subscribe((p) => this.setValue(p));
}
...
public setValue(payload){
this.value = payload;
}
}
注册组件
回答最初的问题,想法是在服务中注册组件,以便它可以根据需要调用组件。您可以通过依赖项注入提取引用,但不建议这样做(例如,如果您的原始组件引用被破坏了怎么办?)
MyAppService
@Injectable()
export class MyAppService {
private myAppComponent: MyAppComponent;
/** here **/
registerMyApp(myApp: MyAppComponent) {
this.myAppComponent = myApp;
}
putValue(payload: JSON){
return this.apiClientService.putAPIObject(payload).then((response) => {
this.myAppComponent.setValue(response);
});
}
}
MyAppComponent
export class MyAppComponent {
public value;
/** and here **/
constructor(myAppService: MyAppService) {
myAppService.registerMyApp(this);
}
...
public setValue(payload){
this.value = payload;
}
}
-
感谢AJT_82指出Angular不希望开发者在服务上使用EventEmitter:
What is the proper use of an EventEmitter?
.