2

i have a trouble about calling a service in my component so the data go null alwyas . this is the example :

the service method :

getOneUser() {
    return this._http.get(globals.serverIp + '/user/getOneUser/' + this._ls.getCurrentUserName(), { headers: this.headers})
      .map((response: Response) => <UserParser> response.json());
  }

the method in component :

updateParametre(message: string){
    let currentUser = new User();

    this._us.getOneUser().subscribe(
      data =>currentUser = data.data,
      error => console.log('error from updateParam ParamtereComponenet ' + error),
      () => console.log(currentUser)
    );
let anotherinstance : User = currentuser ;
console.log(currentUser);
  }

trying to console the currentUser inside the subscribe method:

    {id: 9,
 initials: "YCI",
 nom: "CHABLI",
 prenom: "Yassin",
 password: "$2a$10$iWVnXs/2TwOk7CBr5RuQ.e/1c/BTlxsvkjHyYrtOgKUiRMll2EupO"}

but the object anotherintance go null , and also trying to console the currentUser out of the subscribre go null ..

what is the problem , please ?

Yassine CHABLI
  • 3,459
  • 2
  • 23
  • 43

1 Answers1

0

anotherInstance is scoped to that function. You need to declare it outside of that scope to have a reference to it.

The subscribe method is asynchronous. You are setting anotherInstance to currentUser, but at that time currentUser is just a new User(); It will then be undefined as the function is complete.

Scope your variables appropriately and set their value when you actually have the data:

anotherInstance: User;

updateParametre(message: string){
    let currentUser = new User();

    this._us.getOneUser().subscribe(
      (data) => { 
         currentUser = data.data,
         this.anotherInstance = currentUser
      }
      (error) => console.log(`error from updateParam ParamtereComponenet: ${error}`),
      () => console.log(currentUser)
    );
  }

Then anotherInstance will be a property of your class and accessible outside of the updateParameter method.

joh04667
  • 7,159
  • 27
  • 34
  • but if we try to console : console.log(currentUser) outside the subscribe it's not work on the same varible – Yassine CHABLI May 15 '17 at 22:40
  • No, it is. Your `console.log(currentUser)` outside of the `subscribe` method fires *before* the `subscribe` callbacks do. Outside of `subscribe`, it will *always* be `new User()`. – joh04667 May 15 '17 at 22:44
  • Try this: Console.log a message outside of the `subscribe` method and then console.log another message in the first `subscribe` callback. See which one fires first. – joh04667 May 15 '17 at 22:45