【问题标题】:How to call function in component B when I get an event for this function in Component A当我在组件 A 中获得此函数的事件时如何调用组件 B 中的函数
【发布时间】:2019-12-11 17:06:15
【问题描述】:

当我从 ws 获取事件时,我想使用 Event Emiter:

我有这个获取事件的函数,当我有一个事件时,我想在其他组件中调用一个函数。

组件 A,打字稿代码:

@Output() notify: EventEmitter<any> = new EventEmitter();
getSocketevent() {
  this.socket.on('data', (data) => {
    this.notify.emit(data)
  });
}

组件A,html代码:

<app-component-B (click)='getSocketevent()'></app-component-B>

在组件 B 中我想调用这个函数:

getprod() {
  this.ws.getallprod().subscribe(res => {
    this.dataSource = new MatTableDataSource(res);
    this.dataSource.paginator = this.paginator
  })
}

当我在组件 A 中获得此函数的事件时,如何调用组件 B 中的函数?

【问题讨论】:

标签: angular events eventemitter


【解决方案1】:

来自Component Interaction > Parent calls an @ViewChild()

当父组件类需要这种访问权限时, 将子组件注入到父组件中作为ViewChild

在你的情况下是:

// A component.ts
....
@ViewChild(BComponent, {static: false})
private bComponent: BComponent;

getSocketevent() {
  this.socket.on('data', (data) => {
    // this.notify.emit(data)
    this.bComponent.getprod();
  });
}

StackBlitz Demo

在这种情况下,您可以看到您实际上不需要使用EventEmitter

【讨论】:

    【解决方案2】:

    您可以尝试从父级调用子方法:

    <app-component-B #child (click)='getSocketevent()'></app-component-B> 
    

    ts:

    getSocketevent() {
        var self = this;
        this.socket.on('data', (data) => {
        this.child.getprod(); // call getprod
          this.notify.emit(data)
        });
      }
    

    【讨论】:

    • 孩子?我声明child: any; 并在我获取数据时调用,但错误core.js:9110 ERROR TypeError: Cannot read property 'getprod' of undefined
    • this.child 调用时未定义,请问在哪里调用?
    • 我更改了它但存在错误。 Property 'child' does not exist on type如何声明孩子?
    • 你把#child放在app-component-B标签上吗?
    • 局部变量方法在这种情况下受到限制,因为父子连接必须完全在父模板内完成。在这种情况下,OP 需要从父组件类 (ts) 调用子组件中定义的函数。
    猜你喜欢
    • 1970-01-01
    • 2018-08-07
    • 2017-04-06
    • 2016-03-07
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    相关资源
    最近更新 更多