app.component.ts:
import { Component, OnInit, Inject } from '@angular/core';
import { UserService } from './services/user.service';
import { AuthService } from './services/auth.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor(
private userService: UserService,
private authService: AuthService
) {
}
public ngOnInit() {
const currentToken = localStorage.getItem('xoAuthToken');
if (currentToken) {
const data = { token: currentToken };
this.userService.verifyToken(data)
.subscribe((response: any) => {
if (response.result && response.user) {
this.authService.authenticate(response.user);
}
});
}
}
}
auth.service.ts:
public authenticated = new Subject();
public authenticate(user) {
this.user = user;
this.authenticated.next(this.user);
}
public getUser() {
return this.user;
}
问题是,当我尝试从AuthService获取另一个组件中的用户信息时:
some.component.ts:
public ngOnInit() {
const user = this.authService.getUser();
console.log(user);
}
它尚未初始化,所以我应该在哪里检查localStorage是否有令牌并发出http请求,以便在OnInit的任何组件中,数据已经可用?
答案 0 :(得分:0)
使用该行为主题
public authenticated = new BehaviorSubject(null);
public authenticate(user) {
// Auth function : return undefined if the user failed to login.
this.authenticated.next(this.user);
}
在您的组件中:
public ngOnInit() {
this.authService.authenticated.subscribe(user => {
if (user === null) { /* not logged yet */ }
else if (user === undefined) { /* failed to log in */ }
else if (!!user) { /* is logged */ }
});
}
每次在BSubject上调用next
时,都会触发此订阅。