繁体   English   中英

为什么angular导航时返回false

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM