我有一个身份验证服务,使经过身份验证的变量等于true或false。
checkAuthentication(){
this._authService.getAuthentication()
.subscribe(value => this.authenticated = value);
}
this.authenticated
更改值后如何执行功能? ngOnChanges没有发现变化。
答案 0 :(得分:26)
保持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))
答案 1 :(得分:10)
我认为您可以利用TypeScript的get / set语法来检测服务的经过身份验证的属性何时更新:
private _authenticated:Boolean = false;
get authenticated():Boolean {
return this._authenticated ;
}
set authenticated ( authenticated Boolean) {
// Plugin some processing here
this._ authenticated = 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);
});
}
}
有关详细信息,请参阅此链接:
答案 2 :(得分:1)
这取决于谁需要处理该事件。如果它是父组件,则可以利用输出事件绑定:
@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()">
答案 3 :(得分:-2)
我在组件模板中使用了{{ showValue() }}
,在.ts文件中我调用了服务的变量
showValue() {
this.authenticated = this._authService.authenticated;
return "dummy"
}
感谢Angular2的GUI双向绑定,它可以工作。