从登录组件登录后,我想导航到我的home组件。但是它不导航或加载home组件。下面是我的登录组件。
export class LoginComponent implements OnInit {
loginForm: any;
loading = false;
error = '';
ngOnInit(): void {
this.createForm();
}
constructor(public router: Router, private authService: AuthenticationService, private fb: FormBuilder) {
}
login() {
let credential = this.loginForm.value;
this.authService.authenticate(credential).subscribe((res) => {
if (res) {
this.router.navigate(['/home']);
} else {
this.error = 'user or password is incorrect';
this.loading = false;
}
})
}
createForm() {
this.loginForm = this.fb.group({
userName: null,
password: null
});
}
}
登录函数用于调用身份验证服务。如果服务返回true,则导航到本地组件。身份验证服务返回true,但不导航到本地组件。在下面指定用于验证用户身份的函数
authenticate(credentials): Observable<boolean> {
let options = new RequestOptions({ headers: this.headers });
console.log('option' + JSON.stringify(credentials));
return this.http.post(this.url, JSON.stringify(credentials), options)
.map((response: Response) => {
console.log(response.json());
let token = response.json() && response.json().token;
let shopId = response.json() && response.json().shopId;
if (token) {
window.localStorage.clear();
window.localStorage.setItem('currentUser', JSON.stringify({ username: credentials.userName, token: token, shopId: shopId }));
this.loggedIn.next(true);
return true;
} else {
return false;
}
}).catch((error: any) => Observable.throw(error.json().error));
}
当用户是有效用户时,此函数返回true,并且应基于该登录组件导航到home组件。它返回true,但导航不起作用。