typescript 类型上不存在 Angular2 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42764043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:20:36  来源:igfitidea点击:

Angular2 Property does not exist on type

angulartypescriptangular2-services

提问by Ilan Finkel

I am trying to get my connected user model after login process,

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

First the user is redirecting to "/login" URL after CanActivate guard checked the local storage with the user JSON object and found that it is null

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

Then the user is logging in and redirect back to root URL "/", on the connecting process I'm using AuthService that save the user object that returned from the server in a user model

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

but i'm getting this error:

但我收到此错误:

src/app/_guards/auth.guard.ts (12,48): Property 'token' does not exist on type 'User'.)

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

my user model looks like this:

我的用户模型如下所示:

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

and my AuthService looks like this:

我的 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(['/']);
  }
}

and this is my guard:

这是我的守卫:

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;
    }
}

回答by Tiago Bértolo

Your login method is not static, this means you can only use login after you have created at least one instance of the AuthenticationService.

您的登录方法不是静态的,这意味着您只能在创建至少一个AuthenticationService.

You set currentUserwith nothing in the constructor. And you do not update it after you login.

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

In order to fix it, add:

为了修复它,添加:

this.user = JSON.parse(localStorage.getItem('currentUser'));after localStorage.setItem('currentUser', JSON.stringify(this.user));on line 39.

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

This will probably fix it, even though i do not like it.

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

I made a very similar code recently and my solution for this exact problem was to create a public method such as:

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

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

This way you will always make sure that you get the right value if there is one.

通过这种方式,您将始终确保获得正确的价值(如果有)。

回答by Cengkuru Michael

In your user service module change

在您的用户服务模块更改

getUser(){
    return this.user;
  }

` to

` 到

public getUser(){
    return this.user;
  }
以便它可以访问