Angular2-登录后重定向 [英] Angular2 - redirect after login

查看:170
本文介绍了Angular2-登录后重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在登录后在另一条路线上导航我的用户.

I want to navigate my user on another route after login.

我在文档中发现类似这样的东西应该可以正常工作:

I found out in documentation that something like this should work for it correctly:

this.router.navigate(['/users']);

我在compoenent中的完整方法如下:

My full method in compoenent looks like:

// imports on top
import { Component } from '@angular/core';
import { LoginService } from './login.service';
import { Router } from '@angular/router';

// method somewhere below
login(event, username, password) {
  event.preventDefault();
  let body = JSON.stringify({ username, password });

  this.loginService.login(body)
      .then(res => localStorage.setItem('token', res.msg))
      .catch(error => this.error = error);

  this.router.navigate(['/users']);
}

但是它不会重定向我.基本上,路由会保持不变,并且不会在控制台中发现任何错误.

However it doesn't redirect me. Basically route stays without change and no error spotted in console.

我在做什么错了?

我的路线如下:

const appRoutes: Routes = [
  { path: 'login', component: LoginComponent},
  // users route protected by auth guard
  { path: 'users', component: UsersComponent, canActivate: [AuthGuard] },
  // { path: 'user/:id', component: HeroDetailComponent },
  { path: '**', redirectTo: 'users' }

];

我的AuthGuard看起来像:

My AuthGuard looks like:

export class AuthGuard implements CanActivate {

  constructor(private router: Router) { }

  canActivate() {
    if (localStorage.getItem('token')) {
      // logged in so return true
      return true;
    }

    // not logged in so redirect to login page
    this.router.navigate(['/login']);
    return false;
  }
}

推荐答案

我的

I had a very similar problem on my post. The problem is that there is a delay in authenticating your user but router.navigate executes instantly. As the users part of your site is protected and your technically still unauthenticated, it fails the redirect.

通过在.then上重定向,它会等待您的用户登录,然后,如果成功,它将重定向您的用户.

By redirecting on the .then it waits for your user to login, and then if successful it redirects your user.

尝试使用此:

this.loginService.login(body)
      .then(
            res => localStorage.setItem('token', res.msg)
            this.router.navigate(['/users']);
       )
      .catch(error => this.error = error);

这篇关于Angular2-登录后重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆