ngIf- 检查后表达式已更改。之前的值为:“ngIf:false”。当前值为:“ngIf:true”。

3

当两个组件之间没有父子关系时,如何从一个组件调用另一个组件的方法?

我有两个兄弟组件,如下所示:

header.ts

private postValues() {
   this._PartService.PostDataValues(this.search)
       .subscribe(result => {
       })
}

part.ts

this._PartService.getMasterData()
    .subscribe(result => {
    })

在这种情况下,我需要在getMasterData()中调用postValues()方法来获取一些描述值,并且它没有父子通信。

在part service中新建一个header实例,然后调用它的postValues方法。 - Fateme Fazli
抱歉,我没听懂你的意思。如何做到这一点? - sneha mahalank
请参考以下链接:https://stackoverflow.com/questions/54784980/angular-7-communication-through-service-subscribe-method-called-twice - Mustafa Kunwa
3个回答

2

无法直接触发兄弟组件方法,但是有一种方法可以使用import { BehaviorSubject } from 'rxjs';来触发兄弟组件事件。

我使用这种方法将数据传递给兄弟组件,但如果您触发事件,它也可以工作。

首先,您需要创建一个服务,我称其为DataService.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class DataService {

  private triggerEventMsg = new BehaviorSubject(false);
  triggerEvent = this.triggerEventMsg.asObservable();

  constructor() { }

  triggerEvent(val: boolean) {
    this.messageSource.next(message)
  }

}

现在一个组件可以触发另一个组件,目前是Com1触发Com2事件。
Com1通过传递布尔值来触发DataService的triggerEvent。 Com1.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";

@Component({
  selector: 'app-com1',
  template: `
    {{message}}
    <button (click)="newMessage()">New Message</button>
  `
})
export class Com1 implements OnInit {

  constructor(private data: DataService) { }

  ngOnInit() {

  }

 com1ClickEvent() {
    this.data.triggerEvent(true);
  }

}

当数据发生变化时,观察Com2组件中触发该方法的变量。

Com2.component.ts

import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";

@Component({
  selector: 'app-com2',
  template: `
    <p>Com2</p>
  `
})
export class Com2 implements OnInit {



  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.triggerEventMsg.subscribe(message => {
        // Do What ever you want.

     })
  }

}

1
我的解决方案是使用。
    ngAfterViewChecked(){
      this.cdRef.detectChanges();
    }

在出现错误的组件中。

0

与非父子组件通信。因此,我通过服务进行通信。

service.ts

value=false; 
search: EventEmitter < boolean > = new EventEmitter();
toggle() {
   this.value = !this.value;
   this.search.emit(this.value);
}

search.ts

submit():void{
  this.service.toggle();
}

Home.ts

ngOnInit() {    
   this.service.change.subscribe(value => {
           //some code here
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接