我有一个父容器,其中包含以下内容:
<div id="pageContainer">
<router-outlet></router-outlet>
</div>
<div>
<div class="title">{{text}}</div>
</div>
我还有一个服务,我打算用它来传递子组件(在路由器插座内)到父组件的数据:
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class NotificationsService {
emitChange(change: any) {
return change;
}
}
子组件调用服务方法:
this.notificationsService.emitChange('Data from child');
然后父组件从服务中分配{{text}}:
constructor(
private notificationsService: NotificationsService
) {
notificationsService.emitChange(
text => {
console.log(text);
});
}
但这仍然无效,有什么想法吗?
答案 0 :(得分:0)
使用Subject来做到这一点
import { Injectable } from '@angular/core';
import { Subject, BehaviorSubject } from "rxjs/Rx";
@Injectable()
export class NotificationsService {
emitChange$: Subject<any> = new BehaviorSubject<any>(null);
constructor() { }
emit(value: any) {
this.emitChange$.next(value);
}
get emitChange(): BehaviorSubject<any> {
return (this.emitChange$ as BehaviorSubject<any>);
}
}
在你的孩子身上
this.notificationsService.emit('Data from child');
在父母中
constructor(
private notificationsService: NotificationsService
) {
notificationsService.emitChange.subscribe(
text => {
console.log(text);
});
}
顺便说一下,如果您的子组件直接在父组件中使用,您可以使用EventEmitter在它们之间进行通信。