简体   繁体   English

从子路径到父路径的角度访问方法

[英]Angular access methods of parent routes from child routes

So to explain clearly my problem, I have a component for each of my entities in my application like Author component and Book component. 因此,为清楚说明我的问题,我为应用程序中的每个实体提供了一个组件,例如作者组件和书本组件。 And for each of them I will have two child which is a list component and a form component. 对于他们每个人,我将有两个孩子,分别是列表组件和表单组件。

So basically my route configuration look like this : 所以基本上我的路由配置如下所示:

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 }
        ]
    }
]);

In my AuthorComponent for example I have a method to delete an author that call the service : 例如,在我的AuthorComponent中,我有一个删除调用该服务的作者的方法:

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

My question is how can I call that method from my route child (author list or form component) knowing that I can't call it like a normal child component using event. 我的问题是如何知道自己不能像使用事件那样普通的子组件那样调用它的路由子组件(作者列表或表单组件)中的方法。

PS: I put method (and many other) in the parent because I need to access to it in both child components and so to avoid redundancy. PS:我将方法(以及许多其他方法)放在父级中,因为我需要在两个子组件中都访问它,以便避免冗余。

Standard practice is to use a shared service for Component Interaction . 标准做法是对组件交互使用共享服务。 However, if you still want to avoid using a shared service, you can use the Injector API . 但是,如果仍然要避免使用共享服务,则可以使用Injector API

In your child component, AuthorListComponent for example, do the following: 例如,在您的子组件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');
}

Here is a link to working demo . 这是工作演示的链接。

Use a communication Service which unites several communication observables. 使用将多个通信可观察到的东西结合在一起的通信服务。

An example can be found in the official Angular docs: https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service 可以在Angular官方文档中找到一个示例: https : //angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM