我正在成功登录时使用Angular5 app用户身份验证,api返回令牌。由于某些原因,LoginPageComponent不知道什么是令牌,即使我将它存储在localstorage中,我仍然会得到null。
怎么办?
应用结构: LoginPageComponent
import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Router, ActivatedRoute } from "@angular/router";
import { AuthService } from '../../../shared/auth/auth.service';
@Component({
selector: 'app-login-page',
templateUrl: './login-page.component.html',
styleUrls: ['./login-page.component.scss']
})
export class LoginPageComponent {
@ViewChild('f') loginForm: NgForm;
private user: any = {
email: '',
password: ''
};
constructor(
private auth: AuthService,
private router: Router,
private route: ActivatedRoute) { }
// On submit button click
onSubmit(f: NgForm) {
this.auth.signinUser(f.value.email, f.value.password);
// Returns even signinUser has token
console.log(this.auth.getToken());
}
}
AuthService
signinUser(email: string, password: string) {
this.userService.login(email, password).then(res => {
console.log(res);
this.token = res.token;
// here app has token and this.token contains value
});
}
getToken() {
return this.token;
}
UserService:
login(email, password) {
this.endpoint = this.endpointLocal + '/api/auth/login';
return new Promise(resolve => {
this.http.post(this.endpoint, {"email": email, "password": password})
.subscribe(res => resolve(res.json()));
});
}
答案 0 :(得分:0)
您对then
的调用会调用异步代码,因此在您在onSubmit中调用console.log之前,signinUser
中的Promise的signinUser
部分将不会执行。< / p>
如果您修改AuthService
中的.then
方法以返回承诺,则可以在LoginPageComponent.onSubmit
方法中链接signinUser(email: string, password: string): Promise {
return this.userService.login(email, password).then(res => {
console.log(res);
this.token = res.token;
// here app has token and this.token contains value
});
}
// On submit button click
onSubmit(f: NgForm) {
this.auth.signinUser(f.value.email, f.value.password).then(() => {
console.log(this.auth.getToken());
});
}
来电:
"column not available"