0

I got a problem when I tried to get value with http get services ..

services.ts :

  getLabelTByCode(code: string) {
    return this.http.get('/administration/typeByCode/'+code+'')
      .map((response :Response) => {
        return response.json();
      })
  }

component.ts

name : string;
getTypeByCode(code : string) {
    return this.adminService.getLabelTByCode(code)
      .subscribe(
        label => { 
          this.labelTypeOfDemand = label;
          // Here I can get the value of the name
          return this.labelTypeOfDemand.name;  
        }
      );
  }

saveFolder() { // When I submit my fomrs, I called this method
   this.name = this.getTypeByCode('XER');
   console.log(this.name); // ==> I got undefined
}

Why the value of name is undefined in method saveFolder ? How can I get the value ?

My JSON like :

{
      "id": 9,
      "code": "XER",
      "name": "TEST",
      "status": null
   },
      {
      "id": 7,
      "code": "PBA",
      "name": "TEST",
      "status": null
   },
user1814879
  • 984
  • 6
  • 23
  • 49
  • Change `subscribe(` to `map(` and call `subscribe on `this.getTypeByCode('XER').subscribe(...)` – Günter Zöchbauer Aug 16 '17 at 11:53
  • I tried to do it but in console I got : `Subscriber {closed: false, _parent: null, _parents: null, _subscriptions: Array(1), syncErrorValue: null, …} ` – user1814879 Aug 16 '17 at 12:01
  • This could be a dupe too.. Point is that you cannot return from subscribe: https://stackoverflow.com/questions/39295854/angular-2-how-to-return-data-from-subscribe – AT82 Aug 16 '17 at 12:04
  • You are working with the `Subscription` you get back from `.subscribe(...)`, you need to handle the value in the method you pass to .subscribe(val => { console.log(val);})`. There is no way to go back to sync execution from async execution if this is what you try to achieve. – Günter Zöchbauer Aug 16 '17 at 12:04
  • Thx for reply, but I tried to set a global variable with the result of this but I don't know how I do it with this way.. Like in my code I have `variable name` thatI want to set with the return value of my service – user1814879 Aug 16 '17 at 12:08

0 Answers0