【发布时间】:2023-03-30 00:43:02
【问题描述】:
我有一个登录页面。此登录页面调用(模拟)服务:
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 是一个虚拟项目
【问题讨论】:
-
AuthGuard长什么样子?我的假设是它返回false。