Angular 从另一个组件导入函数

Angular importing function from another component

我有一个 notifications.component,其中有一个函数 test(),我在 settings.component 中有一个按钮,它应该调用这个确切的函数:

  ...
export class NotificationsComponent implements OnInit {
  ...

  test(){
    console.log("Test NotificationsComponent interaction")
  }
}

我尝试将 NotificationsComponent Class 导入 settings.component,并创建了一个函数来调用设置中的 test() 函数,该函数由按钮触发:

import { NotificationsComponent } from './../notifications/notifications.component';
...
export class SettingsComponent implements OnInit {

  constructor(
    private notificationsComponent: NotificationsComponent,
...
    ) { }
...
  testtest(){
    this.notificationsComponent.test()
  }
}

当从 settings.component 触发 testtest() 函数时,我得到了休闲错误:

ERROR Error: "Uncaught (in promise): NullInjectorError: R3InjectorError(SettingsModule)[NotificationsComponent -> NotificationsComponent -> NotificationsComponent -> NotificationsComponent]: 

我想这种方法是完全错误的,但我不明白为什么。我尝试实施其他几种方法,例如 those 但没有成功。 如果有人能指出解决这个问题的方向,我将不胜感激!

创建新服务:

ng generate service notification

将您的方法添加到该服务:

 import { Injectable } from '@angular/core';

@Injectable({   providedIn: 'root' }) export class NotificationService {

  constructor() { }

  test() {
    console.log('Test NotificationsComponent interaction');   } }

将新服务注入您要使用的组件:

import { NotificationsComponent } from './../notifications/notifications.component';
...
export class SettingsComponent implements OnInit {

  constructor(
    private notificationService: NotificationService,
...
    ) { }
...
  testtest(){
    this.notificationService.test()
  }
}

您可以在 Medium 上找到一篇关于 Angular 服务的好文章 here

如果该通知组件在设置组件中

import { ViewChild } from '@angular/core'
import { NotificationsComponent } from './../notifications/notifications.component';

export class SettingsComponent implements OnInit {

  @ViewChild notificationsComponent: NotificationsComponent;

  constructor() { }

  testtest(){
    this.notificationsComponent.test()
  }
}

这会起作用..

否则。将 @Injectable({providedIn:'root'}) 添加到您的 NotificationsComponent

@Injectable({providedIn:'root'})
export class NotificationsComponent implements OnInit {

  test(){
    console.log("Test NotificationsComponent interaction")
  }
}