Angular 4 - 在头部组件和路由组件之间的路由应用程序中传播事件

时间:2018-02-13 17:50:32

标签: angular events angular-routing event-propagation

我有一个主要组件的构造:

<section id="page-container" class="app-page-container">
  <my-app-header></my-app-header>

  <div class="app-content-wrapper">
    <div class="app-content">
      <div class="full-height">
        <router-outlet></router-outlet>
      </div>
    </div>

    <my-app-footer></my-app-footer>
  </div>
</section>

我必须传播一个事件(语言更改就是这个),从AppHeaderComponent(模板中的my-app-header)到路由到的任何组件。 (加载在router-outlet内)。我怎样才能做到这一点?谢谢你的建议!

2 个答案:

答案 0 :(得分:1)

您可以使用共享服务使用 Subject 类型字符串,

selectedLanguage: Subject<string>;

在您的组件中,

setLanguage(selectedValue: any): void {
        this.selectedLanguage = selectedValue;
        this.appService.selectedLanguage.next(this.selectedLanguage);
}   

以及您需要访问的任何地方

this.appService.selectedLanguage.asObservable().subscribe((value: any) => {
    this.selectedLanguage = value;
});

答案 1 :(得分:1)

您必须拥有服务并在组件之间共享。在您的服务中,您将拥有一个可观察的并注册到您想要的每个地方,以及一些改变您的可观察状态的功能。我更喜欢使用BehaviorSubject

您的服务应该是这样的:

export class SomeService {

    showNavigation = new BehaviorSubject<boolean>(false);

    constructor() {
    }

    showBackButton() {
        this.showNavigation.next(true);
    }

    hideBackButton() {
        this.showNavigation.next(false);
    }
}

并在headerComponent中使用它,如下所示:

//inject the service in your constructor
ngOnInit() {
        this.SomeService.showNavigation.subscribe((isShown: boolean) => {
            this.shownavigation = isShown;
        });
    } 

然后,您可以在组件中的任何位置更改状态,同样必须将服务注入组件构造函数。

constructor(private someService: SomeService) {

    this.someService.showBackButton();
}

通过调用方法,您将看到事件正在传播。