Luc*_*uda 3 observable typescript angular
我一直在使用前端的Angular 4和后端的ASP.NET Core 2构建SPA。基本上,给定有效令牌,我试图自动续订用户登录。例如,当我重新加载页面时,我希望Angular保持登录状态。我将令牌以及一个用户对象存储在本地存储中,这样我就可以检查一些用户属性(如果他(她)登录了例)。
我应该如何强制angular等待http请求完成?这是.net获取服务:
get<T>(url: string): Observable<T> {
let options = this.doHeaders();
return this.doSub(this.http.get(this.doUrl(url), options));
}
private doSub<T>(obs: Observable<Response>) {
var ob1: Observable<T> = obs.map(this.extractData)
.catch(this.handleError);
return ob1;
}
Run Code Online (Sandbox Code Playgroud)
这是HTTP请求代码:
getUser() {
if (this.storage.token == null || this.storage.token == '') {
return;
}
this.net.get<LoginModel>(`Authentication/GetUser`).subscribe(t => {
this.storage.token = t.token;
this.storage.user = t.user;
console.log(this.storage.user);
});
}
Run Code Online (Sandbox Code Playgroud)
这是我检查用户的方式:
export class StorageService {
constructor(
private storage: LocalStorageService
) {
}
public user: User = null;
public get isLoggedIn(): boolean {
return this.user != null;
}
Run Code Online (Sandbox Code Playgroud)
}
export class IsLoggedIn implements CanActivate {
constructor(
private storage: StorageService,
private router: Router
) { }
canActivate(
childRoute: ActivatedRouteSnapshot,
state: RouterStateSnapshot
) {
if (this.storage.isLoggedIn) {
return true;
}
this.router.navigate(['account/login'], {
queryParams: {
return: state.url,
message: 'You must be logged in'
}
});
return false;
}}
Run Code Online (Sandbox Code Playgroud)
真正的问题是:每当我尝试在受保护的页面上重新加载页面时,Angular都不会等待http完成,而是将我重定向到登录页面。大约几秒钟后,它登录了,但是我已经被重定向了。上面的代码正在AppComponent(NgOnInit)上执行。提前致谢。
在您的可观察量上使用.toPromise,然后使用async/await.
await this.net.get<LoginModel>(`Authentication/GetUser`).toPromise();
Run Code Online (Sandbox Code Playgroud)
您可以将诺言与async / await一起使用
async getUser() {
if (this.storage.token == null || this.storage.token == '') {
return;
}
const t = await this.net.get<LoginModel>(`Authentication/GetUser`).toPromise();
this.storage.token = t.token;
this.storage.user = t.user;
console.log(this.storage.user);
}
Run Code Online (Sandbox Code Playgroud)
看更多:
| 归档时间: |
|
| 查看次数: |
15087 次 |
| 最近记录: |