Angular 子路由访问父路由的方法

Angular access methods of parent routes from child routes

所以为了清楚地解释我的问题,我在我的应用程序中为我的每个实体都有一个组件,比如 Author 组件和 Book 组件。对于它们中的每一个,我都会有两个子组件,一个是列表组件,一个是表单组件。

基本上我的路由配置是这样的:

export const routing = RouterModule.forRoot([
    {
        path: 'author', component: AuthorComponent,
        children: [
            { path: 'author-list', component: AuthorListComponent },
            { path: 'author-form', component: AuthorFormComponent }
        ]
    },
    {
        path: 'book', component: BookComponent,
        children: [
            { path: 'book-list', component: BookListComponent },
            { path: 'book-form', component: BookFormComponent }
        ]
    }
]);

例如,在我的 AuthorComponent 中,我有一个方法可以删除调用该服务的作者:

deleteBadge = (event): void => {
    // Call delete service
    this._badgeService.delete(event).subscribe(
      result => {
        // Good
      },
      error => {
        // Error
}

我的问题是如何从我的路由子组件(作者列表或表单组件)调用该方法,因为我知道我不能像使用事件的普通子组件那样调用它。

PS:我将方法(和许多其他方法)放在父组件中,因为我需要在两个子组件中访问它,以避免冗余。

使用联合多个通信可观察对象的通信服务。

可以在官方 Angular 文档中找到示例:https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

标准做法是为 Component Interaction. However, if you still want to avoid using a shared service, you can use the Injector API 使用共享服务。

例如,在您的子组件中,AuthorListComponent,执行以下操作:

import { Injector } from '@angular/core';
import {AuthorComponent} from "./author.component";
// ....

constructor(private injector:Injector){
    let parentComponent = this.injector.get(AuthorComponent);
    parentComponent.deleteBadge('String passed from AuthorListComponent');
}

这里是link到working demo