0

I'm getting valid response value from subscriber when I use below code snippets from two different components.

dataService.ts

insertappFormData(){
 return this.http.get('http://localhost:48116/RecuruitmentService.asmx/addRoleTest?i=3').map(this.extractData);
}

private extractData(res: Response) {    
 return res.text() ? res.json() : {}; 
}

app.component.ts

this.dataService.insertappFormData().subscribe((response) =>   console.log(response));

console output

console out put

When I'm trying to assign a variable to response value I'm getting 'undefined' error.

myvar:any;
this.dataService.insertappFormData().subscribe(response => this.myvar =  response);
console.log(this.myvar);

I have already go through the below discussions. Solution-1 , Solution-2

But I couldn't solve it. How to solve this problem?

progman
  • 376
  • 6
  • 15

2 Answers2

2

insertappFormData() returns an observable object which is async. It is executed once you invoke subscribe on it and you should print it out inside subscribe() as:

this.dataService.insertappFormData()
  .subscribe(response => { 
    this.myvar =  response;
    console.log(this.myvar);
});
Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125
1

Because your console.log(this.myvar); is outside of subscribe. Change to this:

this.dataService.insertappFormData().subscribe(response => {
   this.myvar =  response;
   console.log(this.myvar);
});

Note: subscribe is an asynchrone function.

Radonirina Maminiaina
  • 6,958
  • 4
  • 33
  • 60