【问题标题】:Cross component communication with angular 2+ (any child to any parent)与 Angular 2+ 的跨组件通信(任何孩子到任何父母)
【发布时间】:2020-05-29 22:50:45
【问题描述】:

我一直在 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 用户执行一些任务,并且基于该任务我需要增加这些点。

我可以通过 Angular Subject<BroadcastEvent> 中的广播服务实现此功能(在 api 返回值创建广播后,我在组件 A 中列出了该事件),但我不确定是否有更好的方法来做这些事情。 或者我不能在两个组件中使用相同的服务,因为我需要在变量中分配值以及在 DOM 中显示。如果我只需要更新 DOM 元素而不是服务可以解决我的问题,但我还需要组件变量。

【问题讨论】:

标签: angular events event-handling hierarchy broadcast


【解决方案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;
}
}

【讨论】:

  • 感谢您的回答。但在这种情况下,组件 A 将如何知道何时调用 service.getPoints() 方法?
  • 把它放在组件A的模板中。你会看到角度确保显示当前点。
  • 同意两种方式绑定 DOM 元素会更新,但是组件 A 变量呢?它不会反映新的价值。
  • 我看到我们在谈论 2 个不同的事情,我将添加代码。 :)
  • {{myService.getPoints()}} 在组件 A 中是有道理的。但是我有另一种情况,我需要在调用 addPoints() from 之后调用组件 A 中的函数。这可能吗?跨度>
【解决方案2】:

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

@viewchild(ComponentA)ComponentA:ComponentA

在您的 ComponentB 和从 ComponentB 到 ComponentA 的变量或数组的分配结果 api 中。 例如,您在 ComponentA 中定义了一个数组,并且:

组件A

export class componentA { 
    points = [];
}

组件B

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

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

    constructor(private httpClient: HttpClient)

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

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

【讨论】:

    猜你喜欢
    • 2017-07-01
    • 2021-09-19
    • 2021-04-25
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    • 2021-02-18
    • 1970-01-01
    相关资源
    最近更新 更多