0

I have a var User that's undefined after I call my service. Here is the code :

import { User } from './user/user';
import { AppService } from './app.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
})
export class AppComponent implements OnInit  { 

  user: User;

  constructor(
    private appService: AppService,
  ){}

  getUser(): User{
      this.appService.getUser().then(user => { this.user = user; this.setUserRoles();})
      console.log(this.user)
      return this.user
  }

This is my AppService :

import { User } from './user/user';
import { Injectable }    from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()

export class AppService{

    private Url = 'https://cara4-c.na.premiertech.com:451/api/data/';  // URL to web api
    private headers = new Headers({'Content-Type': 'application/json'});

    constructor(private http: Http) { }

    getUser(): Promise<User> {
        return this.http.get(this.Url + 'adfsIdentity')
        .toPromise()
        .then(response => response.json() as User)
        .catch(this.handleError);
    }
    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error); // for demo purposes only
        return Promise.reject(error.message || error);
    }
}

The console.log() show me undefined.

Thanks !

Alex Caron
  • 19
  • 6
  • 1
    Why do you think it should work? – yurzui Jun 14 '17 at 15:28
  • 1
    Hi Alex, could you post you AppService? – Emile Cantero Jun 14 '17 at 15:29
  • @EmileCantero Updated my question – Alex Caron Jun 14 '17 at 15:33
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Saravana Jun 14 '17 at 15:57
  • Possible duplicate of [How do I return the response from an Observable/http/async call in angular2?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2) – AT82 Jun 14 '17 at 18:33

2 Answers2

0

You need to place console.log inside the subscribe,

  this.appService.getUser().then(user => { this.user = user; 
      this.setUserRoles();}
      console.log(this.user)      
  )
  getUser(): User{
     if(this.user){
      return this.user
      };
  }
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

getUser() is as async call so it will take some time update the user value but console statement and will return statement will execute immediately after invoke getUser() call. so return user will return null value

you should your console statement inside then statement.

getUser(): User{
      this.appService.getUser().then(user => { this.user = user; this.setUserRoles();
console.log(this.user);
})
  }
CharanRoot
  • 6,181
  • 2
  • 27
  • 45
  • Ok, but how does I use this.user in another function ? – Alex Caron Jun 14 '17 at 15:33
  • if you want use in another function than you should call that function inside Then. otherwise create User Object while starting App and pass User Object as input to that component. – CharanRoot Jun 14 '17 at 15:45
  • @AlexCaron for exemple you could do that using ngFor but you can do multiple things:
    {{user.data.hosts}}
    – Emile Cantero Jun 14 '17 at 16:01
  • @AlexCaron look that video, for me it help a lot to understand the benefits of using observalbles: https://www.youtube.com/watch?v=VLGCCpOWFFw&t=1676s – Emile Cantero Jun 14 '17 at 16:02
  • as per my knowledge its bad design to create observalbles to manage function call hierarchy inside single component. My suggestion will be create child component and pass as input. – CharanRoot Jun 14 '17 at 16:12
  • @EmileCantero Thank you! I'm using appComponent.users in my *ngIf and now it's working! :) – Alex Caron Jun 14 '17 at 17:09
  • @AlexCaron you welcome please vote and flag my answear if it was helpful – Emile Cantero Jun 15 '17 at 07:27