[英]Why does the angular returns false when navigating
我有一個登錄頁面。 此登錄頁面調用(模擬)服務:
async onSubmit() {
this.isLoading.next(true);
await this.authService.login(
this.loginForm.value.email,
this.loginForm.value.password
);
this.isLoading.next(false);
}
該服務目前是一個虛擬的:
export class AuthService {
private _user = new BehaviorSubject<User>(null);
get user() {
return this._user.asObservable();
}
constructor() {}
async login(username: string, password: string) {
await new Promise((resolve) => setTimeout(resolve, 500)); // To mock service
this._user.next({
name: 'Julien',
avatarUrl: 'https://randomuser.me/api/portraits/men/1.jpg',
});
}
}
在我的登錄頁面中,我已注冊到我的服務用戶:
ngOnInit() {
this.loginForm = new FormGroup({
email: new FormControl('', {
validators: [Validators.required, Validators.email],
}),
password: new FormControl('', { validators: [Validators.required] }),
});
this.userSubscription = this.authService.user.subscribe(async (user) => {
if (user) {
console.log('User logged in, going to /');
console.log(user);
if (await this.router.navigate(['/'])) {
console.log('with success');
} else {
console.log('with failure');
}
}
});
}
因此,當我輸入電子郵件+密碼,提交表單時,我會看到用戶訂閱的 3 個 console.logs。 一個表示正在調用訂閱(並且該用戶不是空的),第二個按預期顯示用戶,但第三個表示“失敗”,並且路由器沒有導航到 /。
為什么會這樣? 我的路線也很簡單:
const routes: Routes = [
{ path: '', redirectTo: 'chat', pathMatch: 'full' },
{
path: 'chat',
loadChildren: () => import('./chat/chat.module').then((m) => m.ChatModule),
canLoad: [AuthGuard],
},
{
path: 'auth',
loadChildren: () => import('./auth/auth.module').then((m) => m.AuthModule),
},
];
完整代碼可在此處獲得: https://j4n.visualstudio.com/_git/WebMessenger?path=%2F&version=GBfeature%2Flogin-page&_a=contents
向一些同事介紹 angular 是一個虛擬項目
我在stackblitz上試過了,我發現它正在工作。 我看到它返回錯誤的唯一情況是導航沒有發生(由於警衛不允許它或路線相同)。 例如,如果您在組件 A 中,並且您嘗試再次導航到組件 A,則不會發生導航,因為路線沒有變化。 但是,如果您在組件 A 中,但導航到組件 B,則它返回 true。 我想在你的情況下,你已經在 '/' 路線上。 因此,它不會再次導航。 希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.