[英]Angular2 - subscribe to Service variable changes
我有一个身份验证服务,使经过身份验证的变量等于true或false。
checkAuthentication(){
this._authService.getAuthentication()
.subscribe(value => this.authenticated = value);
}
当this.authenticated
更改值时,如何执行函数? ngOnChanges没有发现变化。
要在服务中进行authenticated
并在组件之间共享,可以使用BehaviorSubject
,在不同的地方检查身份验证的value
,以及对更改做出反应的subscribe()
方法...
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!")
}
}
当
this.authenticated
更改值时,如何执行函数?
this._authService.authenticated
.subscribe((value: boolean) => console.log(value))
我认为您可以利用TypeScript的get / set语法来检测服务的经过身份验证的属性何时更新:
private _authenticated:Boolean = false;
get authenticated():Boolean {
return this._authenticated ;
}
set authenticated ( authenticated Boolean) {
// Plugin some processing here
this._ authenticated = authenticated;
}
分配值时,将调用“set authenticated”块。 例如,使用这样的代码:
this.authenticated = true;
有关详细信息,请参阅此问题:
也就是说你也可以利用服务中的EventEmitter属性。 更新authenticated属性后,可以触发相应的事件。
export class AuthService {
authenticatedChange: Subject<boolean> = new Subject();
constructor() {}
emit(authenticated) {
this.authenticatedChange.next(authenticated);
}
subscribe(component, callback) {
// set 'this' to component when callback is called
return this.authenticatedChange.subscribe(data => {
callback(component, data);
});
}
}
有关详细信息,请参阅此链接:
这取决于谁需要处理该事件。 如果它是父组件,您可以利用输出事件绑定:
@Output authenticationChange: EventEmitter<Boolean> = new EventEmitter();
checkAuthentication(){
this._authService.getAuthentication()
.subscribe(value =>
if(value != this.authenticated) {
this.authenticated = value);
this.authenticationChange.emit(value);
});
}
在您的父组件中:
<directive (authenticationChange)="doSomething()">
我在组件模板中使用了{{ showValue() }}
,在.ts文件中我调用了服务的变量
showValue() {
this.authenticated = this._authService.authenticated;
return "dummy"
}
感谢Angular2的GUI双向绑定,它可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.