Angular 2组件听着服务中的变化
根据布尔更改的方式,您可以在服务上将其公开为Observable<boolean>
,然后在组件中订阅该流。你的服务看起来是这样的:
@Injectable()
export class MyBooleanService {
myBool$: Observable<boolean>;
private boolSubject: Subject<boolean>;
constructor() {
this.boolSubject = new Subject<boolean>();
this.myBool$ = this.boolSubject.asObservable();
}
...some code that emits new values using this.boolSubject...
}
然后在你的组件,你会有这样的事情:
@Component({...})
export class MyComponent {
currentBool: boolean;
constructor(service: MyBooleanService) {
service.myBool$.subscribe((newBool: boolean) => { this.currentBool = newBool; });
}
}
现在取决于你需要与布尔值做什么,你可能需要做一些其他的东西让你的组件更新,但这是使用observable的要点。
另一种选择是在模板中使用异步管道,而不是显式订阅构造函数中的流。同样,这取决于你需要用bool值做什么。
非常感谢您的帮助! –
你可以从rxjs主题 –
** ** UserService.ts' this._dataService.get
山姆的回答是完全正确的。我只想补充一点,你也可以利用一个打字稿二传手自动触发更改事件:
@Injectable()
export class MyBooleanService {
myBool$: Observable<boolean>;
private boolSubject: Subject<boolean>;
constructor() {
this.boolSubject = new Subject<boolean>();
this.myBool$ = this.boolSubject.asObservable();
}
set myBool(newValue) {
this._myBool = newValue;
this.boolSubject.next(newValue);
}
}
嗨,'this._myBool'从哪里来?不知道对不起 – Lloople
它应该是一个私人布尔服务,他只是忘了把它包括在他的示例代码。 –
见https://angular.io/docs/ts/latest/cookbook/component-communication.html #!#双向服务 –
酷感谢提示! –
@MarkRajcok感谢分享! Angular 2的文档真的出现了......我不知道他们在那里有这样的例子。 –