【问题标题】:How to invoke a method of one component from the other [Angular]如何从另一个 [Angular] 调用一个组件的方法
【发布时间】:2020-03-13 07:38:56
【问题描述】:

我是网络开发的新手。我正在做一个 Angular 项目。我有两个组件,filter-panelfilter-bar。他们都不是彼此的亲子关系。我检查了一些解决方案,例如:

Access a method of one component from another

以及互联网上的许多其他解决方案。

我尝试了两种方法:

  1. @ViewChild

  2. 角度服务

    但我仍然遇到错误。

ERROR TypeError: "_co.filterPanel is undefined"

这是我的代码。

filter-bar.component.html

<button (click)="filterPanel.filterPanelMethod()">Call</button>

filter-bar.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { FilterPanelComponent } from './filter-panel/filter-panel.component';
import { FilterPanelService } from './filter-panel/filter-panel.service';

@Component({
    selector: 'app-filter-bar',
    templateUrl: './filter-bar.component.html'
})
export class FilterBarComponent implements OnInit {
    @ViewChild(FilterPanelComponent, {static : false}) public filterPanel: FilterPanelComponent;
   
    constructor(public filterPanelService: FilterPanelService) {      
      //filterPanelService.filterPanelMethod();
    }

    ngOnInit() {
    }
}

filter-panel.component.ts

import { Component, OnInit } from '@angular/core';
import {FilterPanelService} from './filter-panel.service';
@Component({
    selector: 'app-filter-panel',
    templateUrl: './filter-panel.component.html'
})
export class FilterPanelComponent implements OnInit {

    constructor(public filterPanelService:FilterPanelService) {
    }

    filterPanelMethod() {
      console.log("I'm filter-panel method");
    }

    ngOnInit() {}
}

这里不涉及数据发送或接收。我只是想看看这个方法是如何被调用的,剩下的我来处理。我确定我在某个地方犯了一个可怕的错误。我还创建了一个stackblitz。恐怕我混合了两种方法,让自己更加困惑。请纠正我。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    如果您想使用 @ViewChild 访问 FilterPanelComponent,则需要将 FilterPanelComponent 放在 FilterBarComponent 视图中。现在您在应用程序组件中同时使用它们,这就是您无法访问它的原因。如果您想在它们之间提供通信,我建议您创建一个带有 Subject 的服务,其中一个会监听该服务,然后在预期时采取行动。

    另一种解决方案,但相当丑陋的是

    1. AppComponent 中访问 @ViewChild(FilterPanelComponent, {static : false}) public filterPanel: FilterPanelComponent;
    2. 点击按钮时从FilterBarComponentAppComponent发出事件
    3. AppComponent 中监听该事件并从 FilterPanelComponent 调用方法

    【讨论】:

    • 我已经改变了我的堆栈闪电战,你能看看吗
    • 所以ViewChild 不再需要。
    • 如果您使用服务,则不再需要 ViewChild。
    • 好的,那我只使用服务。现在我将运行一些单元测试用例并更新您。但是,此解决方案有效,我接受了。谢谢:-)
    【解决方案2】:

    您需要进行以下两项更改:

    1. 从 filter-bar.component.html 调用过滤器面板

      <app-filter-panel></app-filter-panel>
      
    2. 在 filter-bar.component.ts 中,您需要使用 this 访问服务引用。例如:

       this.filterPanelService.someMethod();
      

    【讨论】:

    • 但是先生,他们不应该是亲子关系。让我们放弃这种方法。我正在尝试一些解决方案。
    • 为什么他们不能成为父母孩子?似乎是一个 XY 问题,您要调用哪个特定方法以及它背后的功能是什么?
    • 这是一个非常复杂的项目。所以我只是试图让事情保持简单,从而创建了我想学习的概念的堆栈闪电战。
    猜你喜欢
    • 1970-01-01
    • 2017-12-08
    • 2018-04-14
    • 2017-05-19
    • 1970-01-01
    • 2017-08-19
    • 2019-02-03
    • 2018-05-06
    相关资源
    最近更新 更多