【问题标题】:Angular2 Property does not exist on type类型上不存在 Angular2 属性
【发布时间】:2023-03-26 01:39:01
【问题描述】:

我正在尝试在登录过程后获取我的连接用户模型,

CanActivate 守卫使用用户 JSON 对象检查本地存储并发现它为空后,首先用户重定向到“/login” URL

然后用户正在登录并重定向回根 URL“/”, 在连接过程中,我使用 AuthService 将从服务器返回的用户对象保存在用户模型中

但我收到此错误:

src/app/_guards/auth.guard.ts (12,48):“用户”类型上不存在属性“令牌”。)

我的用户模型如下所示:

export class User {
constructor(
    public email:string,
    public passowrd:string,
    public firstname:string,
    public lastname:string,
    public token:string
){}
}

我的 AuthService 看起来像这样:

import { Injectable } from '@angular/core';
import { User } from "../_models/user";
import { Observable } from 'rxjs/Rx';
import { Http, Headers, Response } from '@angular/http';
import { Router } from "@angular/router";
import 'rxjs/add/operator/map';

@Injectable()
export class AuthenticationService {
  private user: User;

  constructor(private http: Http,private router:Router) {
    // set token if saved in local storage
    var currentUser = JSON.parse(localStorage.getItem('currentUser'));
    this.user = currentUser;
  }

  getUser(){
    return this.user;
  }

    login(email:string,password:string): Observable<boolean> {
        const body = JSON.stringify({ email: email, password: password });
        const headers = new Headers({
         'Content-Type' : 'application/json'
        });

        return this.http.get("https://test.firebaseio.com/users.json",{headers:headers})
            .map(
            (response: Response) => {

                // login successful if there's a token in the response
                let token = response.json() && response.json().token;
                if(token){
                    // set user object
                    this.user = response.json();

                    // store username and jwt token in local storage to keep user logged in between page refreshes
                    localStorage.setItem('currentUser', JSON.stringify(this.user));

            // return true to indicate successful login
                    return true;
                } else {
                    // return false to indicate failed login
                    return false;
                }
                //return response.json();
            }
          );
    }

    logout(): void {
    // clear token remove user from local storage to log user out
    this.user = null;
    localStorage.removeItem('currentUser');
    this.router.navigate(['/']);
  }
}

这是我的后卫:

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { AuthenticationService } from '../_services/index';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private router: Router,private authService:AuthenticationService) { }

    canActivate(route:ActivatedRouteSnapshot, state:RouterStateSnapshot): boolean {
        if (this.authService.getUser().token) {
            // logged in so return true
            return true;
        }

        this.router.navigate(['/login']);
        return false;
    }
}

【问题讨论】:

  • 哪个打字稿版本?
  • 版本是2.0.3

标签: angular typescript angular2-services


【解决方案1】:

您的登录方法不是静态的,这意味着您只能在创建至少一个AuthenticationService 实例后才能使用登录。

您在构造函数中设置了 currentUser 没有任何内容。而且您登录后不会更新它。

为了修复它,添加:

this.user = JSON.parse(localStorage.getItem('currentUser')); 在第 39 行 localStorage.setItem('currentUser', JSON.stringify(this.user)); 之后。

这可能会解决它,即使我不喜欢它。

我最近编写了一个非常相似的代码,我对这个确切问题的解决方案是创建一个公共方法,例如:

  public getAuthKey() {
    return localStorage.getItem('currentUser');
  }

这样,您将始终确保获得正确的值(如果有的话)。

【讨论】:

  • 您在身份验证服务中添加了 getAuthKey() 函数吗?
  • 现在可以使用了,谢谢 Tiago!买我还在试图理解为什么......
  • this.http.get 是一个异步调用。在this.authService.getUser().token 之后,您第一次运行localStorage.setItem...。
【解决方案2】:

在您的用户服务模块中更改

getUser(){
    return this.user;
  }

`到

public getUser(){
    return this.user;
  }
使其可访问

【讨论】:

猜你喜欢
  • 2017-01-14
  • 1970-01-01
  • 2017-10-21
  • 1970-01-01
  • 2017-12-20
  • 2016-09-14
  • 1970-01-01
  • 1970-01-01
  • 2017-04-27
相关资源
最近更新 更多