Angular2 - 订阅服务变量的变化 [英] Angular2 - subscribe to Service variable changes
问题描述
我有一个认证服务,使身份验证的变量为真或假。
checkAuthentication(){
this._authService.getAuthentication()
.subscribe(价值=> this.authenticated =值);
}
在 this.authenticated
已经改变了价值我如何执行一个功能? ngOnChanges不拿起变化。
要保持验证
服务,你可以用组件之间共享
BehaviorSubject
,这是值
在不同的地方,检查认证,它的订阅()
方法对变化做出反应......
类AuthService {
公开验证=新BehaviorSubject(NULL);
getAuthentication(){
this._http.get('/身份验证)
.MAP(响应= GT; response.json())
.MAP(JSON =>布尔(JSON))//或任何检查你需要...
.subscribe((价值:布尔)=> this.authenticated.next(值))
}
}类Component {
constuctor(私人_authService:AuthService){
//只检查一次,即使组件
//破坏并重新构建
如果(this._authService.authenticated.value ===空)
this._authService.getAuthentication();
} 的onSubmit(){
如果(!this._authService.authenticated.value)
抛出新的错误(你验证!)
}
}
如何当
this.authenticated
已经改变了我的价值执行一个功能?
块引用>this._authService.authenticated
.subscribe((价值:布尔)=>的console.log(值))I have an authentication service that makes the authenticated variable equal to true or false.
checkAuthentication(){ this._authService.getAuthentication() .subscribe(value => this.authenticated = value); }
How do I execute a function when
this.authenticated
has changed value? ngOnChanges is not picking up the change.解决方案To keep
authenticated
in service and share it between components you can useBehaviorSubject
, it'svalue
to check authentication in different places, and it'ssubscribe()
method to react on change...class AuthService { public authenticated = new BehaviorSubject(null); getAuthentication() { this._http.get('/authenticate') .map(response => response.json()) .map(json => Boolean(json)) // or whatever check you need... .subscribe((value: boolean) => this.authenticated.next(value)) } } class Component { constuctor(private _authService: AuthService) { // Only check once even if component is // destroyed and constructed again if (this._authService.authenticated.value === null) this._authService.getAuthentication(); } onSubmit(){ if (!this._authService.authenticated.value) throw new Error("You are authenticated!") } }
How do I execute a function when
this.authenticated
has changed value?
this._authService.authenticated .subscribe((value: boolean) => console.log(value))
这篇关于Angular2 - 订阅服务变量的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!