hanik
hanik

Reputation: 129

Angular 8: Property in Service is returning undefined

I have an interface for User in Angular,

export interface User {
    id: number;
    firstName: string;
    lastName: string;
}

I have a UserService,

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { User } from './model/user';

export class UserService {
    static instance: UserService;
    user: User;

    constructor(private httpClient: HttpClient) { 
       if(!UserService.instance) {
          UserService.instance = this;
       }

       return UserService.instance;
    }

    getUserData() {
       return this.httpClient.get(URL);
    }

    setUserData(data) {
       this.user = data;
    }

    getUser() {
       return this.user;
    }
}

I am maintaining Service as Singleton since I want to have single access to logged in user data and share state between different areas of app.

In user.component.ts

export class UserComponent implements OnInit {

  constructor(private userService: UserService) { }

  ngOnInit() {
    this.userService.getUserData(url).subscribe((response: any) => {
        this.userService.setUserData(response);
    });
  }

  getUser() {
     console.log(this.userService.getUser()) //prints undefined.
  }

}

user in UserService is undefined, when I debug. I am missing out something and I can't figure it out. Can you guys please help.

Upvotes: 0

Views: 831

Answers (2)

hanik
hanik

Reputation: 129

Property user in UserService class is defined of type User, but it is not initialized. Therefore, we are getting undefined error. You can initialize it as follows,

user:User = <User>{};

Upvotes: 0

leonmain
leonmain

Reputation: 344

Add this decorator to your service so as to make it singleton in Angular way:

@Injectable({providedIn: 'root'})
export class UserService {
...
}

After that you will be getting the same instance of the service wherever it's injected.

Upvotes: 1

Related Questions