【问题标题】:component communication using service使用服务进行组件通信
【发布时间】:2020-04-19 04:20:01
【问题描述】:

在我的 Angular 6 中,我正在使用服务进行组件通信:

service.ts

import { Injectable, Inject } from '@angular/core';
import { Subject } from 'rxjs';
//import { Subject }    from 'rxjs/Subject';
@Injectable()
export class ComponentCommunicationService {
  private notify = new Subject<any>();
  /**
   * Observable string streams
   */
  notifyObservable$ = this.notify.asObservable();

  constructor(){}

  public notifyOther(data: any) {
    if (data) {
      this.notify.next(data);
    }
  }
}

在我的父组件 P 中,我正在检查是否满足某些条件,它应该启动服务调用。

let isRoleFound= true;
 if(this.isRoleFound){
      this.componentCommunicationService.notifyOther({value:this.isRoleFound,option:'call from menu'});
      this.ref.detectChanges();
    }

子组件 C 中的服务调用:

import {ComponentCommunicationService} from 'libs/services-module/src/commonservice/componentcommunication.service'
 constructor(
    private componentCommunicationService:ComponentCommunicationService
  ) { }

      ngOnInit() {
       this.componentCommunicationService.notifyObservable$.subscribe(res => {
          if (res.hasOwnProperty('option') && res.option === 'call from menu') {
            console.log(res.value)
            this.isRoldFound= res.value;

          }
      }) 
    }

这里调用是从父组件实例化的,它进入子组件ngOnInit生命周期钩子,但最终它没有进入if循环并跳出。

请注意,子组件是类似于菜单的子菜单,只有当您将鼠标悬停在菜单项上时才会出现。

【问题讨论】:

    标签: angular


    【解决方案1】:

    不确定您在问什么,但这可能是时间问题。父母在孩子订阅之前触发主题。改用重播主题:

    private notify = new ReplaySubject<any>(1);
    

    重播主题向新订阅者重播他们的价值观。

    【讨论】:

    • 就是这样,你能帮我解决主题和行为主题之间的实际区别
    猜你喜欢
    • 2018-01-29
    • 2014-03-18
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 2019-11-15
    相关资源
    最近更新 更多