如何在angular2中实现路由器插座到父同步通信?

时间:2016-09-28 10:44:06

标签: angular

我有一个仪表板组件,如下所示

@Component({
    selector: 'dashboard',   
    template: '<category-list></category-list>
               <header-top></header-top>
               <router-outlet></router-outlet>'
})

export class Dashboard{  
    constructor() { 
    } 
}

类别列表组件列出了仪表板侧栏页面中的所有类别,以及&#39; / dashboard&#39;的基本路由。首先在路由器插座中加载所有列表(其中还有编辑选项,在这里编辑时也应该更改),与父母兄弟姐妹沟通路由器插座子的最佳方式是什么?

category-list组件是

@Component({
    selector: 'category-list',   
    template: "all category list"
})

export class DashboardCategoryList{  
    constructor() { 
    } 
}

路由器插座内的子组件看起来像

@Component({
    selector: 'category-list-edit',   
    template: ''
})

export class DashboardCategoryList{  
    constructor() { 
    } 
}

category-list-edit中的编辑应该反映在类别列表中,如何实现?

1 个答案:

答案 0 :(得分:1)

您可以从根组件注入服务,以便在整个应用中提供相同的实例。在该服务中有一个活动,并从EventEmitter订阅category-list,并在进行某些编辑时从category-list-edit发出活动:

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

@Injectable()
export class CategoryService {
  categoryListEdited: EventEmitter<any> = new EventEmitter<any>();
  constructor() {}
}

@Component({
    selector: 'category-list-edit',   
    template: ''
})
export class DashboardCategoryListEdit{  
    constructor(private categoryService: CategoryService) { 
    } 

    edit(){
        //edits made here
        this.categoryService.categoryListEdited.emit({});
    }
}

@Component({
    selector: 'category-list',   
    template: "all category list"
})
export class DashboardCategoryList{  
    constructor(private categoryService: CategoryService) { 
        this.categoryService.categoryListEdited.subscribe(data => {
            console.log("something was changed in category-list-edit");
        });
    } 
}
相关问题