2016-03-28 90 views
12

我有一个关于变化检测的简单问题。Angular 2组件听着服务中的变化

我有一个组件和一个布尔内部的(全局)服务。 如何让组件侦听该布尔值并在该布尔变化时执行一个函数?

谢谢!

+2

见https://angular.io/docs/ts/latest/cookbook/component-communication.html #!#双向服务 –

+0

酷感谢提示! –

+0

@MarkRajcok感谢分享! Angular 2的文档真的出现了......我不知道他们在那里有这样的例子。 –

回答

17

根据布尔更改的方式,您可以在服务上将其公开为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值做什么。

+0

非常感谢您的帮助! –

+2

你可以从rxjs主题 –

+0

** ** UserService.ts' this._dataService.get (this._userUrl) .subscribe(用户=> { self.user = Enumerable.from(用户).firstOrDefault( E => e.Email ==用户名密码&& == “1234”);如果 (!! self.user){ self._isLoggedInSubject.next(TRUE);} });' **组件** 'isLoggedIn:boolean; 构造函数(private _userService:UserService){ this._userService.isLoggedIn.subscribe((response:boolean)=> this.isLoggedIn = response); }' 没有为我工作 – nadav

10

山姆的回答是完全正确的。我只想补充一点,你也可以利用一个打字稿二传手自动触发更改事件:

@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); 
    } 
} 
+4

嗨,'this._myBool'从哪里来?不知道对不起 – Lloople

+0

它应该是一个私人布尔服务,他只是忘了把它包括在他的示例代码。 –