为什么我不能在Angular Guard中记录事情?

时间:2018-12-17 09:39:14

标签: angular routes

我有一条由守卫保护的路线不起作用。当我尝试使用console.log进行调试时,没有任何反应。我想念什么?

这是我的app-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ForetagsprofilComponent } from 
import { UserHasJwtToken } from './guards/user-has-jwt-token.guard';

const appRoutes: Routes = [
  {
    path: '',
    component: SearchForetagsprofilComponent
  },
  {
    path: 'redigera',
    component: ForetagsprofilComponent,
    canActivate: [UserHasJwtToken]
  }

这是我的后卫用户has-jwt-token.guard.ts:

import { Injectable, OnInit } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AfUserService } from '../services/af-user-service';
import { AfUserInfo } from '../model/af-user-info';

@Injectable()
export class UserHasJwtToken implements CanActivate, OnInit {

  private _afUserInfo = new AfUserInfo();
  constructor(private afUserService: AfUserService, private router: Router) {
  }

  ngOnInit(): void {
    this.afUserService.getUserInfo().subscribe(response => {
      this._afUserInfo = response;
    });

    console.log('Customernumber: ' + this.afUserService.getUserInfo());
  }

2 个答案:

答案 0 :(得分:1)

canActivate(): Observable<boolean> {
this.afUserService.getUserInfo().subscribe(response => {
      this._afUserInfo = response;
    });

    console.log('Customernumber: ' + this.afUserService.getUserInfo());
}

这会很好!

答案 1 :(得分:1)

您缺少一个canActivate方法,该方法需要返回布尔值或可观察值。您的情况如下:

canActivate() {
  console.log('Checking if there is user info');
  // I am not subscribing here. I am just returning the observable.
  // Router will subscribe to it on each call.
  return this.afUserService.getUserInfo()
  .pipe(
     // We do, however, wanna log the response 
     tap(response => console.log('Got response:', response);
     // Also, we wanna return a boolean. E.g if there's a property `isLoggedIn`on the response.
     // if we return true, the routing happens. if we return false, the router blocks the route.
     map(response => response.isLoggedIn),
  );

canActivate方法是您从Angular导入并尝试实现的 CanActivate 接口的一部分。也许您的IDE(例如VS代码)警告您缺少此方法-您应检查这些类型的错误,它们会立即向您指出问题。您可以运行诸如ng lint之类的程序,以在将来检查此类问题。