Angular 6 通过服务在 2 个组件实例之间进行通信

Angular 6 communicate between 2 components instances through service

我有一个组件 loads/remove 通过调用服务动态地另一个组件。 我还为动态添加组件提供了删除自身的能力。我的问题是通知其他组件此动态组件实例已删除。

我曾尝试使用事件 output/emit 和 subject/subscribe,但没有成功。不确定我是否做错了。

这是我的代码,单击按钮并添加组件后,如果我在组件内使用关闭按钮,主按钮将不知道这一点,需要单击 2 次才能向右切换,加上按钮的文本将是错误的

https://stackblitz.com/edit/dynamically-row-components-for-smart-table

我在使用主题并订阅它时遇到的问题会触发所有实例而不会影响按钮!

您可以做几件事来让它工作,而不是为所有组件订阅一个公共主题或事件发射器,为每个组件动态创建一个独特的主题。所以它不会为所有组件触发。为此,您首先需要为每个组件提供一个唯一的 componentName,或者您可以使用 id。

data = [
    {
      id: 1,
      name: 'Leanne Graham',
      username: 'Bret',
      email: 'Sincere@april.biz',
      button: 'Button #1',
      componentName:"component"+1
    }

第 2 步:根据 componentNae 为每行创建注册主题。每次关闭时,相应的订阅将调用,然后您可以从此处删除该组件

    ngOnInit() {
        this.renderValue = this.value.toString().toUpperCase();
         this.InjiService.componentSubjects[this.rowData.componentName] = new Subject();
         this.InjiService.componentSubjects[this.rowData.componentName].subscribe(()=>{

          this.InjiService.removeComponent(this.expanededComp);
          this.expanededComp = null;
          //this.renderValue = this.value.toString().toUpperCase(); //"Open";
          this.isOpen = false;
          //firing the change detection manually
          this.ref.markForCheck();    
        });

  }

请确保您在服务中声明了 componentSubjects

export class InjiService {
 public componentSubjects: { [name: string]: Subject<any> } = {};

Working sample