簡體   English   中英

從子路徑到父路徑的角度訪問方法

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

因此,為清楚說明我的問題,我為應用程序中的每個實體提供了一個組件,例如作者組件和書本組件。 對於他們每個人,我將有兩個孩子,分別是列表組件和表單組件。

所以基本上我的路由配置如下所示:

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:我將方法(以及許多其他方法)放在父級中,因為我需要在兩個子組件中都訪問它,以便避免冗余。

標准做法是對組件交互使用共享服務。 但是,如果仍然要避免使用共享服務,則可以使用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');
}

這是工作演示的鏈接。

使用將多個通信可觀察到的東西結合在一起的通信服務。

可以在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