【问题标题】:Communicating between different module's component function不同模块的组件功能之间的通信
【发布时间】:2020-10-30 21:01:26
【问题描述】:

我有两个组件 ComponentA 和 ComponentB。这两个组件在不同的模块中声明。现在我想从 ComponentB 调用 ComponentA 函数。这两个组件没有父子关系。

export class ComponentA{
 randomfun(){
 console.log('random function entered');
 }
}
constructor(private comA: ComponentA){}
export class ComponentB{
// calling component A function
comA.randomfun();
}

此代码导致 StaticInjectorError(AppModule)[ComponentB -> ComponentA]

【问题讨论】:

  • 使用服务在组件之间进行通信:angular.io/guide/…(在订阅函数中,调用组件的函数)。啊!女巫模块中的每一个都定义了它是无关紧要的
  • 我没听懂最后一句话。
  • 对不起我的英语,我想说组件可以在不同的模块中,也可以不在(都是一样的)

标签: angular module components


【解决方案1】:

您可以使用shared singleton service

  @Injectable({
      providedIn: 'root'
    })
    export class SharedService {
        private _invokeSource: Subject<void> = new Subject<void>();
        public invokeObservable: Observable<void> = this._invokeSource.asObservable();
        public invoke(): void {
            this._invokeSource.next();
    }
    }

组件 A:

[...]this.sharedService.invoke();

组件 B:

[...]

private _subscription: Subscription;
this._subscription = this.sharedService.invokeObservable.subscribe(() => this.randomfun())

此外,为避免内存泄漏,您应该在ngOnDestroy() 期间取消订阅自定义可观察对象:

public ngOnDestroy(){
    this._subscription.unsubscribe();
}

演示:https://stackblitz.com/edit/angular-shared-service-invoke

请注意,如果您尝试调用其方法的组件未加载到 dom 中,这将不起作用。在这种情况下,您将不得不创建组件类的实例并在其上调用方法(尽管我永远不建议这样做)。

【讨论】:

  • randomfun 在类型“ComponentB”上不存在。你能提供任何工作演示吗
  • randomfun() 显然是您要调用的任何方法。我添加了一个详细的演示来展示这种方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-08
  • 2020-10-16
  • 1970-01-01
  • 2013-06-07
相关资源
最近更新 更多