簡體   English   中英

Angular 2 canActivate 承諾命中遠程服務

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

首先,我不確定這是處理這個問題的最佳方法,但我正在尋找的是“/”上的路由守衛,它檢查用戶是否登錄,如果是,則將它們重定向到“/dashboard” . 我想在加載路由之前執行此操作,以避免由於在遠程服務器上檢查身份驗證狀態而導致屏幕閃爍。

我正在實現 canActivate 接口,但它沒有按預期工作。 它點擊身份驗證服務,並返回用戶,根據此測試代碼應該重定向用戶,但我在控制台中看到用戶但沒有重定向。

這是代碼

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”綁定而發生的。 由於“this”不是您的組件類實例,您的代碼很可能會在 console.log 之后進入 catch 塊。 使用“胖箭頭”來解決這個問題。 喜歡:

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