通过服务的通信不工作 Angular 8

Communication via service isn't working Angular 8

我正在做一个项目,其中 parents 和 children 需要通过服务进行通信。按照官方文档中的this article,我无法使其正常工作。

这是我创建的服务:

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);
    }
}

在parent组件中,我导入所有我需要的:

@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);
    }

}

这是 child 的代码:

@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 时,child 没有响应。有什么建议吗?

谢谢!

您的子组件 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>

勾选 working Demo Here:

可能存在几个问题:

  1. 检查child和parent组件是否有相同的服务实例。您可以提供 CommonService 多个位置,因此 parent 和 child 可能不会共享 class.

  2. 的相同实例
  3. 你具体是如何执行tellChild()方法的?也许你在 parent 组件启动时执行了该方法,因此 Observable 发出了新事件,但 child 尚未创建且未订阅 Observable,它会跳过该事件。

可能的解决方案:

  • 如果问题 2 是你的情况,那么我建议你更新你的 CommonService 以使用 BehaviorSubject 而不是 Subject。 private _propertyChangeAnnouncedSource = new BehaviorSubject<string>(null); 这样无论有人什么时候订阅 Observable,他们都将获得最新的值并继续监控进一步的变化。如果你想避免由于 BehaviorSubject 导致的初始 null 值,我建议你像这样修改 Observable:propertyChangeAnnounced$ = this._propertyChangeAnnouncedSource.asObservable() .pipe(filter(x => x !== null));

暂时就这些了,让我们听听您对这 2 个问题的看法,如果问题仍然存在,我稍后会更新我的回复。