简体   繁体   English

Angular 2 canActivate 承诺命中远程服务

[英]Angular 2 canActivate with a promise hitting a remote service

Firstly, I am not sure that this is the best way to handle this problem, but what I am looking for is a route guard on "/" which checks if the user is logged in, if so to redirect them to "/dashboard".首先,我不确定这是处理这个问题的最佳方法,但我正在寻找的是“/”上的路由守卫,它检查用户是否登录,如果是,则将它们重定向到“/dashboard” . I would like to do this before the route is loaded, to avoid a screen flashing since were checking auth status on a remote server.我想在加载路由之前执行此操作,以避免由于在远程服务器上检查身份验证状态而导致屏幕闪烁。

I am implementing the canActivate interface, but its not working as expected.我正在实现 canActivate 接口,但它没有按预期工作。 It hits the auth service, and returns the user, which according to this test code should redirect the user, but instead I am seeing the user in the console but no redirect.它点击身份验证服务,并返回用户,根据此测试代码应该重定向用户,但我在控制台中看到用户但没有重定向。

Here is the code这是代码

import { Injectable }               from '@angular/core';
import { Router, CanActivate }      from '@angular/router';

import { Observable }               from 'rxjs/Observable';

import { User }                     from './../../models/user.model';
import { AuthService }              from './auth.service';

@Injectable()
export class HomeAuthGuard implements CanActivate {
  constructor(
    private router: Router,
    private authService: AuthService
  ) {}

  canActivate(): Promise<boolean> {
    return new Promise((resolve) => {
      this.authService.getStatus()
        .then(function (user: User) {
          console.log('home auth', user)
          this.router.navigate(['/dashboard']);
          resolve(false);
        })
        .catch(function () {
          resolve(true);
        });
      });
  }
}

This is happen because of 'this' binding.这是由于“this”绑定而发生的。 Mostly likely your code goes to catch block after console.log due to fact that 'this' is not your component class instance.由于“this”不是您的组件类实例,您的代码很可能会在 console.log 之后进入 catch 块。 Use "fat arrow" to solve this issue.使用“胖箭头”来解决这个问题。 like:喜欢:

return new Promise((resolve) => {
  this.authService.getStatus()
    .then((user: User) => {
      console.log('home auth', user)
      this.router.navigate(['/dashboard']);
      resolve(false);
    })
    .catch(err => {
      resolve(true);
    });
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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