【发布时间】: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