mohit mohit - 24 days ago 7
reST (reStructuredText) Question

Angular 2 observable not assigning returned object to variable

getEmployee(id : number) : void{
var e : Employee;
this.http.get(this.employeesUrl + '/' + id)
.map(response => <Employee>response.json())
.subscribe((res) =>{e = res},
(err)=>console.log(err),
()=>console.log("Done"));

console.log(e.Name);

}


This res that is returned on doing console.log(res) prints the employee object correctly. But when i try to assign it to a variable it gives me a page long error. Although it does print Done at the end.
Have spent 3 hrs. on these and have gone through lot of SO posts but can't figure it out

Answer

If you log the response like

   var e : Employee;
   this.http.get(this.employeesUrl + '/' + id)
   .map(response => <Employee>response.json())
   .subscribe((res) =>{e = res},
                      (err)=>console.log(err),
                      ()=>console.log("Done"));

 console.log(e.Name);  

Of course you will see a blank/error status since the above code(this.http.get) is async. Meaning you are making a request then you are waiting for the response inside subscribe and when it comes, you will assign e to res or print whatever you want. While waiting you are already logging(e.Name). And since "e" is initially undefined, e.Name is an error.

Instead try this and check the log,

   var e : Employee;
   this.http.get(this.employeesUrl + '/' + id)
   .map(response => <Employee>response.json())
   .subscribe((res) =>{
               e = res;
               console.log(e.Name); 
               },
              (err)=>console.log(err),
              ()=>console.log("Done"));

What you should do:

Let this method return an observable and lets say the components name is GetEmployeeService,

getEmployee(id : number) : Observable<Employee>{
       return this.http.get(this.employeesUrl + '/' + id)
       .map(response => <Employee>response.json())

}

and subscribe to this observable wherever(in the class that calls this service) you want to use it

constructor(..., private myService: getEmployeeService)

...
//the place where you need the response
this.myService.subscribe((res)={
   console.log(res);
   //do something with res here
   this.field = res;
})