我有一个AuthService,我正在从LoginComponent调用signInAction方法。我想在令牌初始化时重定向。
我该怎么做?
这是我的auth.service.ts文件中的SignIn方法
ngOnInit() {
this.authService.signInAction();
//Wait until signInAction is complete before navigateByUrl
this.router.navigateByUrl('/my-profile');
}
这是我的LoginComponent文件
signInAction(){
let that = this;
return Observable.create(observer =>
new Oidc.UserManager(this.config).signinRedirectCallback().then(function (user) {
that.currentUser = user;
that.token = user.access_token;
observer.next();
observer.complete();
}).catch(function (e) {
console.error(e);
observer.complete();
})
);
}
/ 更新后的工作版 / 感谢大家,我学会了Observable的工作方式,这是我的最终工作版本。
//在AuthService
中ngOnInit() {
this.authService.signInAction()
.subscribe(
() => this.router.navigateByUrl('/my-profile')
);
}
//在我的LoginComponent中
<div class="wrapper">
<div class="flex-container">
<img class="container-video" src="http://placehold.it/600x250">
<img class="container-video" src="http://placehold.it/300x250">
<img class="container-video" src="http://placehold.it/920x300">
<img class="container-video" src="http://placehold.it/450x250">
<img class="container-video" src="http://placehold.it/450x250">
<img class="container-video" src="http://placehold.it/300x300">
<img class="container-video" src="http://placehold.it/250x300">
<img class="container-video" src="http://placehold.it/330x300">
<img class="container-video" src="http://placehold.it/920x350">
<img class="container-video" src="http://placehold.it/600x250">
<img class="container-video" src="http://placehold.it/300x250">
</div>
</div>
答案 0 :(得分:0)
可能有更好的方法。但是,您现在可以使用EventEmitter并在组件上订阅它来解决此问题:
import { EventEmitter } from '@angular/core';
在服务类中定义事件发射器并在令牌更新后发出事件:
tokenUpdated = new EventEmitter<void>();
signInAction() {
let that = this;
new Oidc.UserManager(this.config).signinRedirectCallback().then(function (user) {
that.currentUser = user;
that.token = user.access_token;
that.tokenUpdated.emit();
}).catch(function (e) {
console.error(e);
});
}
然后,在您的组件中,您可以订阅它:
ngOnInit() {
this.authService.signInAction();
//Wait until signInAction is complete before navigateByUrl
this.authService.tokenUpdated
.subscribe(
() => this.router.navigateByUrl('/my-profile')
);
}
答案 1 :(得分:0)
我会同意所有会告诉你使用observable的答案,但为了获得你必须工作的目的,你可以使用简单的回调。
this.authService.signInAction((user) => {
this.router.navigateByUrl('/my-profile');
});
// ---
signInAction(next){
let that = this;
new Oidc.UserManager(this.config)
.signinRedirectCallback()
.then(function (user) {
that.currentUser = user;
that.token = user.access_token;
next(user);