这个概念看起来很难看,与Angular相比1.我仍然无法得到如何通知我所有其他组件的变化。假设我有HeaderComponent,我将按钮更改语言属性从'en'到'de'。我在EventEmitter中绑定事件,但是如何在其他组件中获取新属性?
import { Component, Output, EventEmitter, Input } from '@angular/core'
import { ROUTER_DIRECTIVES, Router } from '@angular/router';
import {Observable} from 'rxjs/Observable';
@Component({
selector: 'bp-header',
templateUrl: 'app/header.component.html',
directives: [ROUTER_DIRECTIVES]
})
export class HeaderComponent {
isActive: number;
language: string = "en";
constructor(private dataService: DataService) {
}
ngOnInit() {
this.isActive = 1;
}
public setLanguage = (language: string) => {
if (this.language === language) { return }
else { this.language = language };
this.dataService.changeLanguage(language);
}
private setActive(active: number) {
if (this.isActive === active) return;
this.isActive = active;
}
}
这是另一个子组件。我是对的,输入应该听取变化吗?
import { Component, Input } from '@angular/core';
import { Person } from './data.person';
import { Article } from './data.article';
import { ROUTER_DIRECTIVES, Router } from '@angular/router';
@Component({
selector: 'bp-home',
templateUrl: "app/home.component.html",
directives: [ROUTER_DIRECTIVES]
})
export class HomeComponent {
language: string;
article: Article;
persons: Person[];
subscription: Subscription;
constructor(private dataService: DataService) {
this.subscription = dataService.languageChanged$.subscribe(
language => {
this.language = language;
});
}
ngOnInit() {
this.article = this.language == "ru" ? this.articleRu : this.articleEn;
this.persons = this.language == "ru" ? this.personsRu : this.personsEn;
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
ngOnChanges() {
this.article = this.language == "ru" ? this.articleRu : this.articleEn;
this.persons = this.language == "ru" ? this.personsRu : this.personsEn;
}
这是数据服务:
import { Component, Injectable} from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class DataService {
private language = new Subject<string>();
languageChanged$ = this.language.asObservable();
changeLanguage(language: string) {
this.language.next(language);
}
}