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

Angular 4 - event propagation in routed app between header component and routed component

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

<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 内加载)。我怎样才能做到这一点?谢谢大家的建议!

您可以使用共享服务使用 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;
});

您必须拥有一项服务并在您的组件之间共享该服务。在您的服务中,您将有一个可观察对象并在您想要的任何地方注册,还有一些函数可以改变您的可观察状态。我更喜欢使用 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();
}

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