Ilan Finkel
Ilan Finkel

Reputation: 496

Angular2 Property does not exist on type

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

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

but i'm getting this error:

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

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:

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

Upvotes: 3

Views: 20715

Answers (2)

Cengkuru Michael
Cengkuru Michael

Reputation: 4780

In your user service module change

getUser(){
    return this.user;
  }

` to

public getUser(){
    return this.user;
  }
so that it is accessible

Upvotes: -2

Tiago B&#233;rtolo
Tiago B&#233;rtolo

Reputation: 4343

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

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

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 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.

Upvotes: 4

Related Questions