【问题标题】:Why not working in app.component but in auth.guard?为什么不在 app.component 中工作,而在 auth.guard 中工作?
【发布时间】:2017-03-01 17:47:40
【问题描述】:

我不明白为什么在 auth.guard 中完美运行的 app.component 中无法使用相同的代码。

我已经编写了一些代码来检查用户是否登录到服务器,并在路由定义的 auth.guard 中使用了 canActivate,如下所示

路由

{ path: 'dashboard',  component: DashboardComponent , canActivate: [AuthGuard] }

AuthGuard

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService} from './services/auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
      constructor(private authService:AuthService, private router:Router) { }
          canActivate(next:ActivatedRouteSnapshot, state:RouterStateSnapshot) {
              return this.authService.isAuth().map(e => {
                  if (e) {
                      return true;
                  }
              }).catch(() => {
                  this.router.navigate(['/login']);
                  return Observable.of(false);
              });
          }
    }

它工作正常,但在 AppComponent 中不工作 应用组件

import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from './services/auth.service';
@Component({
  moduleId: module.id,
  selector: 'my-app',
  templateUrl: './views/app.component.html',
  styleUrls: [ './styles/app.component.css' ]
})
export class AppComponent implements OnInit{
  title = 'Jiffy';
  status:boolean;
  swap:boolean=true;
  constructor(authService:AuthService, private router:Router){
    return this.authService.isAuth().map(e => {
        if (e) {
            return true;
        }
    }).catch(() => {
        this.router.navigate(['/login']);
        return Observable.of(false);
    });
  }
}

我不明白为什么它在这里工作?

错误

错误:未捕获(承诺中):TypeError:无法读取属性“isAuth” 未定义的类型错误:无法读取未定义的属性“isAuth” 新的应用组件

AuthService

  isAuth(){
        return this.http.get("/account/check")
        .map(function(res){
          return status=res.json().status;
        });
    }

带 Passport 的 Express 服务器

router.get('/check',  function(req, res,next) {
  if (req.isAuthenticated()){
    return  res.send({"status":true});
  }
    return res.send({"status":false});
});

【问题讨论】:

  • 您可以提供更多详细信息吗?记录任何错误? isAuth 在每种情况下的结果是什么?
  • 已编辑关于服务和服务器方法。我正在使用 Passport,它返回 true 或 false

标签: javascript angular routing


【解决方案1】:

如果要在组件中使用this 获取参数,则需要将publicprivate 添加到构造函数中的参数。

constructor(private authService:AuthService, private router:Router)

【讨论】:

    【解决方案2】:

    错误是说authService 未定义。您是否在 app.module 中将 AuthService 声明为提供程序?

    【讨论】:

    • 我认为你需要在构造函数中添加private关键字,否则Angular不会知道注入服务。
    猜你喜欢
    • 2017-08-19
    • 1970-01-01
    • 2017-11-19
    • 2013-07-01
    • 2017-07-28
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多