首页 > 解决方案 > angular.router 在离子应用程序中无法按预期工作

问题描述

我在从一页路由到另一页时遇到问题。我有一个登录页面,它是我的应用程序的主页,所以当登录成功时,我会从登录页面导航到个人资料页面。配置文件页面在 ion-router-outlet 中加载,但登录页面不会移开并且始终显示。 AuthService 在登录提交时调用

authenticationState = new BehaviorSubject(false);
  constructor(
    private msgService: MessagesService,
    private http: HTTP,
    private router: Router,
    private storage: Storage,
    private plt: Platform
  ) {
    this.plt.ready().then(() => {
      this.checkToken();
    });
  }

  login({ email, password }) {
    this.loading = true;
    this.http
      .post(
        'some link for getting token',
        {
          username: email,
          password
        },
        { 'Content-Type': 'application/json' }
      )
      .then(data => {
        const res = JSON.parse(data.data);
        if (res.status == 'success') {
          this.msgService.addMessage('Login successfull', 'success');
          console.log(res.data);
          this.storage.set('token', res.data.token).then(() => {
            this.authenticationState.next(true);
            this.router.navigate(['profile']).then(() => {
              console.log('going to profile');
            });
            this.loading = false;
          });
        } else if (res.status == 'error') {
          console.log(res);
          this.msgService.addMessage(res.message, 'danger');
          this.loading = false;
          this.clearRecords();
        }
      })
      .catch(error => {
        console.log(error);
        this.msgService.addMessage('Internal server error', 'danger');
        this.loading = false;
        this.clearRecords();
      });
  }

路由页面.ts

{
    path: 'login',
    // loadChildren: './pages/auth/login/login.module#LoginPageModule'
    loadChildren: () =>
      import('./pages/auth/login/login.module').then(m => m.LoginPageModule)
  },
  {
    path: 'register',
    loadChildren: './pages/auth/register/register.module#RegisterPageModule'
  },
  {
    path: 'profile',
    //canActivate: [AuthGuard],
    loadChildren: './pages/profile/profile.module#ProfilePageModule'
  },

app.component.ts

initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      this.authService.authenticationState.subscribe(state => {
        if (state) {
          this.router.navigate(['profile']);
        } else {
          this.router.navigate(['login']);
        }
      });
    });
  }

调试模式下的路由器插座 在 此处输入图像描述

标签: angularauthenticationionic4angular-router

解决方案


推荐阅读