Angular:如何从不同模块中的另一个组件调用组件方法 [英] Angular: How to call component method from another component in different modules

查看:711
本文介绍了Angular:如何从不同模块中的另一个组件调用组件方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从B_Module拥有的B_Component中调用A_Module拥有的A_Component的方法,并在将A_Component作为参数添加到B_Component构造函数中时得到以下错误:

I am trying to call a method of A_Component owned by A_Module from B_Component owned by B_Module and am getting the following error as soon as I add A_Component as a parameter to the B_Component constructor:

NullInjectorError:没有A_Component的提供者!

NullInjectorError: No provider for A_Component!

这两个组件不是父/子.它们的模块由app.module导入

The two components are not parent/child. Their modules are imported by app.module

(为简洁起见,代码摘要)

(Code summarized for brevity)

A_Module:

import { A_Component } from '...'

@NgModule({
    imports: [...],
    declarations: [A_Component],
    exports: [A_Component],
})

export class A_Module { }

B_Module:

import { A_Module } from '...'
import { B_Component } from '...'

@NgModule({
    imports: [A_Module],
    declarations: [B_Component]
})

export class B_Module { }

A_Component:

A_Component:

export class A_Component {
    someMethod() {...}
}

B_Component:

B_Component:

import { A_Component } from '...'

export class B_Component {

    constructor(public a_Component: A_Component)) {} //this param causes error

    callSomeMethod() {
        this.a_Component.someMethod();
    }
}

这不是如何在模块之间调用组件方法吗?唯一的方法就是通过服务吗?

Is this not how to call component methods across modules? Is the only way to do this is with a service?

推荐答案

请参考组件交互官方文档.

您只能使用来调用在组件内部声明的组件方法. ViewChild .

如果要使两个不同的组件相互交互-应该完成

If you want to make two different component interact with each other - it should be done via common service.

在@diopside中的点之后更新

这篇关于Angular:如何从不同模块中的另一个组件调用组件方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆