0

I would like to display a username of the current user in my angular 2 application. The backend is developed with .net core web api.

I write this code but obtain in console this error :

TypeError: Cannot read property 'UserName' of undefined

class AuthService

import {Injectable, EventEmitter} from "@angular/core";
import {Http, Headers, Response, RequestOptions} from "@angular/http";
import {Observable} from "rxjs/Observable";
import {AuthHttp} from "./auth.http";
import {User} from "./user";

@Injectable()

export class AuthService {
    authKey = "auth";

    constructor(private http: AuthHttp) {
    }

    // Persist auth into localStorage or removes it if a NULL argument is given
    setAuth(auth: any): boolean {
        if (auth) {
            localStorage.setItem(this.authKey, JSON.stringify(auth));
        }
        else {
            localStorage.removeItem(this.authKey);
        }
        return true;
    }

    // Retrieves the auth JSON object (or NULL if none)
    getAuth(): any {
        var i = localStorage.getItem(this.authKey);
        if (i) {
            return JSON.parse(i);
        }
        else {
            return null;
        }
    }

    // Returns TRUE if the user is logged in, FALSE otherwise.

    isLoggedIn(): boolean {
        return localStorage.getItem(this.authKey) != null;
    }

    **get() {
        return this.http.get("api/Accounts")
            .map(response => <User>response.json());
    }**

}

I'm sure that the user is logged in because I can read the his token.

Web api method

 /// <summary>
        /// GET: api/accounts
        /// </summary>
        /// <returns>A Json-serialized object representing the current account.</returns>
        [HttpGet()]
        public IActionResult Get()
        {
            var id = GetCurrentUserId(); 
            //var id = User.FindFirst(ClaimTypes.NameIdentifier).Value;
            var user = DbContext.Users.Where(i => i.Id == id).FirstOrDefault();
            if (user != null) return new JsonResult(new UserViewModel()
            {
                Type = user.Type,
                UserName = user.UserName,
                Email = user.Email,
                DisplayName = user.DisplayName,
                PhoneNumber = user.PhoneNumber,
                DisplayPhoneNumber = user.DisplayPhoneNumber,
                Description = user.Description

            }, DefaultJsonSettings);
            else return NotFound(new { error = String.Format("User ID {0} has not been found", id) });
        }

class user in typescript

export class User {
    constructor(
        public Type: number,
        public UserName: string,
        public DisplayName: string,
        public PhoneNumber: string,
        public DisplayPhoneNumber: boolean,
        public Description: string,
        public Password: string,
        public PasswordNew: string,
        public Email: string
    ) {
    }
}

Code of component in angular 2

import {Component, OnInit} from "@angular/core";
import {Router, ActivatedRoute} from "@angular/router";
import {AuthService} from "./auth.service";
import {AuthHttp} from "./auth.http";
import {User} from "./user";

@Component({
    selector: "home",
    templateUrl: "templates/home.component.html",
    //template: `<h1>Home Component</h1>`
})

export class HomeComponent {

    isRegister: boolean;
    currentUser: User;
    constructor(
        public router: Router,
        public authService: AuthService,
        private activatedRoute: ActivatedRoute
    ) {

        //this.isRegister = this.authService.isLoggedIn();
        //console.log(this.isRegister);
    }
    ngOnInit() {
        if (this.authService.isLoggedIn()) {
            this.authService.get().subscribe(
                User => this.currentUser = User
            );           
            console.log(this.isRegister);
            console.log(this.currentUser.UserName);               
        }
    }
}

Code template html

 <div *ngIf="currentUser"><h1>{{currentUser.UserName}}</h1></div>

I don't understand why this doesn't work.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Cicciux
  • 177
  • 4
  • 19

2 Answers2

0

you'are trying to access the this.currentUser.UserName before this.authService.get() resolves User value, because this.authService.get is asynchronous, so do this :

     ngOnInit() {
        if (this.authService.isLoggedIn()) {
            this.authService.get().subscribe(
                User => {
                  this.currentUser = User
                  console.log(this.isRegister);
                  console.log(this.currentUser.UserName);
            });           

        }
    }
El houcine bougarfaoui
  • 35,805
  • 9
  • 37
  • 37
0

try to replace:

currentUser: User;

as

currentUser = new User();

Undefined error in console is disappeared.

Sompob
  • 21
  • 1