与角2+的跨组件通信(任何孩子到任何父母)

问题描述 投票:0回答:2

我一直在Angular 2+中开发Web应用程序。而且我有以下情况

component A
  |
  component B
    |
    component C
      |
      component D   //click on button -> call apis and return value to component A's variable 

component D中,如果用户单击,则有一个按钮,我们需要调用rest API,并且该API的结果应显示在component A中。

[业务案例:考虑component A是您的顶部标题,其中包含点数,并且表格component D用户执行某些任务,并且基于该任务,我需要增加该点。

我可以通过角度Subject<BroadcastEvent>中的广播服务来实现此功能(在api返回值创建广播之后,并且在组件A中我列出了该事件),但是我不确定是否有更好的方法来执行此操作。否则我无法在两个组件中使用相同的服务,因为我需要在变量以及DOM中的show中分配值。如果我只需要更新DOM元素,则服务可以解决我的问题,但是我也需要组件变量。

angular events event-handling hierarchy broadcast
2个回答
1
投票

以我的经验,使服务保持分数是有意义的。然后将该服务注入组件D中,以调用service.addPoints()。该服务也被注入到组件A中以调用service.getPoints()。

componentA.component.ts:

export class componentA  {

constructor(public myService: MyService){}

}

componentA.component.html:

{{myService.getPoints()}}

componentD.component.ts:

export class componentD  {

constructor(public myService: MyService){}

}

componentD.component.html:

<button (click)="{{myService.addPoints()"></button>

myService.ts:

@Injectable()
export class MyService {
public points: number;

public getPoints(){
  return this.points;
}

public addPoints(){
  this.points = this.points +1;
}
}

0
投票

如果您以ComponentB方法调用您的api,则可以使用

@@ viewchild(ComponentA)ComponentA:ComponentA

在您的ComponentB和Assignment结果api中,从ComponentB到ComponentA的变量或数组。例如,您在ComponentA中定义一个数组,然后:

ComponentA

export class componentA { 
    points = [];
}

ComponentB

import { HttpClient } from '@angular/common/http';

export class ComponentB { 
    @viewchild(ComponentA)ComponentA:ComponentA;

    constructor(private httpClient: HttpClient)

    GetPoints() {
    this.httpClient.get(your url).subscribe(
      result=>{
        ComponentA.points.push(result);
              }
               }
}

但是这种方式不是最好的方式,您应该创建一个服务并在组件之间传递数据,如上述答案,但这也是我希望能够提供帮助的一种方式。


-1
投票

您可以通过输入/输出/ veiwChild或行为主体使用父子关系可能帮助您的链接。行为主题-> learningangularjs.net/global-data-sharing-in-angular-4.php组件通讯-> https://www.pluralsight.com/guides/angular-communication-between-components-input-output-properties

© www.soinside.com 2019 - 2024. All rights reserved.