【问题标题】:Why does the angular returns false when navigating为什么导航时角度返回false
【发布时间】: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

标签: angular angular-routing


【解决方案1】:

我在stackblitz 上试用了它,我发现它正在工作。我看到它返回错误的唯一情况是导航没有发生(由于警卫不允许它或路线相同)。例如,如果您在组件 A 中并尝试再次导航到组件 A,则不会发生导航,因为路径没有变化。但是,如果您在组件 A 中,但导航到组件 B,则它返回 true。我想在你的情况下,你已经在 '/' 路线上。因此,它不会再次导航。希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2013-09-18
    • 2011-05-22
    • 2014-11-17
    • 2014-03-11
    • 2019-07-12
    • 2012-08-24
    • 2013-03-08
    • 2016-09-02
    相关资源
    最近更新 更多