我正在尝试创建一个能够使用api令牌作为日志记录方法使用REST API的Ionic v3应用程序。
用户执行登录后,变量 currentUser 将被设置,从现在开始,AuthInterceptor将始终发送附加到所有请求的api令牌。
但是,显然 currentUser 始终为null,即使用作检查的登录中的警报始终显示正确的用户名。
AuthInterceptor.ts
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
currentUser: any;
constructor(public storage: Storage) {
this.storage.get('currentUser').then((val) => {
this.currentUser = JSON.parse(val);
});
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add authorization header with api token if available
console.log(this.currentUser);
if (this.currentUser && this.currentUser.api_token) {
request = request.clone({
setHeaders: {
'Authorization': `Bearer ${this.currentUser.api_token}`
}
});
}
return next.handle(request);
}
}
AuthSvc.ts
login(email: string, password: string) {
return this.http.post<any>('login', { email: email, password: password })
.map(data => {
// login successful if there's an api token in the response
if (data.user && data.user.api_token) {
this.setUser(data.user);
return data.user;
}
});
}
setUser(user) {
console.log('setUser');
// store user details and the token in local storage to keep user logged in between page refreshes
this.storage.set("currentUser", JSON.stringify(user));
}
login.ts(页面)
this.authSvc.login(this.user.email, this.user.password)
.subscribe(
data => {
alert('Hi '+data.name);
this.navCtrl.setRoot(HomePage);
},
error => {
});
API返回一个由
组成的JSON对象{
"success": true,
"user": User obj
}