我正在做一个项目,家长和孩子需要通过服务进行沟通。遵循正式文档中的这篇文章,我无法使它工作。
这是我创建的服务:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable()
export class CommonService {
private _propertyChangeAnnouncedSource = new Subject<string>();
propertyChangeAnnounced$ = this._propertyChangeAnnouncedSource.asObservable();
public announcePropertyChange(data: string) {
this._propertyChangeAnnouncedSource.next(data);
}
}在父组件中,我导入所需的所有内容:
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss'],
providers: [CommonService]
})
export class ParentComponent implements OnInit {
constructor(private _commonService: CommonService) {
}
tellChild(data): void {
this._commonService.announcePropertyChange(data);
}
}这是孩子的守则:
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit, OnDestroy {
private subscription: Subscription;
constructor(private _commonService: CommonService) {
this.subscription = this._commonService.propertyChangeAnnounced$.subscribe(
data => {
console.log(data);
});
}
}当我调用announcePropertyChange时,孩子没有响应。有什么建议吗?
谢谢!
发布于 2019-07-12 11:51:35
可能有几个问题:
CommonService提供几个位置,因此父级和子级可能不会共享该类的同一个实例。tellChild()方法?可能在启动父组件时执行该方法,因此新事件由可观察性发出,但子事件尚未创建,也未订阅可观测性,它跳过事件。可能的解决办法:
private _propertyChangeAnnouncedSource = new BehaviorSubject<string>(null);是这样的,无论什么时候有人订阅可观察到的值,他们都会得到最新的值,并继续监视进一步的更改。如果您想避免由于null而导致的初始BehaviorSubject值,我建议您修改可观察到的如下:propertyChangeAnnounced$ = this._propertyChangeAnnouncedSource.asObservable() .pipe(filter(x => x !== null));这是现在,让我们听取你的这2,我会更新我的回应,稍后如果仍然有问题。
发布于 2019-07-11 21:22:43
您的子组件中似乎有一个constructor错误。
private subscription;
constructor(private _commonService: CommonService) {
this.subscription = this._commonService.propertyChangeAnnounced$.subscribe(
data => {
console.log(data,'from child');
});
}这对我有用。此外,请说明如何在代码中调用tellChild:
<button (click)="tellChild('TestData')">Tell child</button>检查这里的工作演示:
https://stackoverflow.com/questions/56997261
复制相似问题