我向REST API发送请求并且登录成功后,我想导航到另一个页面。 我发现我需要使用异步并等待它。
login.component.ts:
onLoginSubmit() {
this.submitted = true;
if (this.loginForm.invalid) {
return;
}
this.loginService.login(this.loginForm.value.username, this.loginForm.value.password).then(async (result: AuthModel) => {
this.cookieService.set('token', result.token);
console.log(result.token, result.succes);
await this.router.navigateByUrl['dashboard'];
},(error) => {
console.log(error);
this.router.navigateByUrl['/dashboard'];
});
}
auth.service.ts:
async login(username: string, password: string): Promise<AuthReturnModel> {
const loginModel: LoginModel = new LoginModel();
loginModel.username = username;
loginModel.password = password;
let authReturnModel: AuthReturnModel;
await this.httpClient.post<AuthReturnModel>(API_URL +"/users/login", loginModel)
.pipe(
map((data: AuthReturnModel) => authReturnModel = data)
).pipe(
catchError(error => of(`Bad Promise: ${error}`))
).toPromise();
return authReturnModel;
}
页面“ dashboard”将不会加载? 预先谢谢你。
答案 0 :(得分:1)
也许您在navigationByUrl调用中缺少了/
this.router.navigateByUrl['/dashboard'];
另外,我认为您不需要在navigationByUrl之前等待,如果使用then,您已经在异步调用中了。
Here,您可以找到使用angular登录的完整示例/教程。 该示例中使用的登录调用为:
login(){
console.log(this.loginForm.value);
this.isSubmitted = true;
if(this.loginForm.invalid){
return;
}
this.authService.login(this.loginForm.value);
this.router.navigateByUrl('/admin');
}
答案 1 :(得分:0)
在auth服务中,您将返回authReturnModel,但在组件中,您将期待一个承诺。 (您已使用then
来捕获结果。)
我认为,因为您使用的是Promise,所以无需使用异步等待就可以使用它,
login(username: string, password: string): Promise<AuthReturnModel> {
const loginModel: LoginModel = new LoginModel();
loginModel.username = username;
loginModel.password = password;
let authReturnModel: AuthReturnModel;
return this.httpClient.post<AuthReturnModel>(API_URL +"/users/login", loginModel)
.pipe(
map((data: AuthReturnModel) => authReturnModel = data),
catchError(error => of(`Bad Promise: ${error}`))
).toPromise();
}
组件。
this.loginService.login(this.loginForm.value.username, this.loginForm.value.password).then((result: AuthModel) => {
this.cookieService.set('token', result.token);
console.log(result.token, result.succes);
this.router.navigateByUrl['dashboard'];
},(error) => {
console.log(error);
this.router.navigateByUrl['/dashboard'];
});
}