2

I'm trying to create a trigger using angular, but when I get the response from my api it returns me undefined.

Here's my global-search.ts file:

export class GlobalSearchComponent{
    searchable: String = '';
    professionals: any = {}; 

    constructor(public client: Http){
    }

    getProfessionals() {
        return this.client.get('professionals')
                   .subscribe(data => this.professionals = data.json());
    }
    doSearch(ev: any) {
        let val = ev.target.value;
        if(val.length > 3) {
            this.getProfessionals();
            console.log(this.professionals);
        }
    }

if in getProfessionals() method I do:

return this.client.get('professionals'
              .subscribe(data => console.log(data.json()));

It returns me an object(and it's right), but in doSearch() method, it shows me undefined.

What am I doing wrong?

Phil
  • 157,677
  • 23
  • 242
  • 245

1 Answers1

1

The problem you're having is because of where your console.log statement is.

Observable/ .subscribe is asynchronous, so it will allow the rest of your code to continue executing while it waits for the data to come back from your service, and then will update the this.professionals variable when that completes.

In your original code, you call the getProfessionals function from doSearch, and while the .subscribe is still being fulfilled (and the this.professionals variable is still undefined), the code continues and logs out that value (undefined), and then the data comes back and the variable is set to the correct value, but by this point the console has already logged out the previous state.

If you move the console.log statement into the .subscribe block after the response is received, you'll find it logs out the actual value you're expecting, as the console.log won't execute until the response is received and the value assigned to your variable.

export class GlobalSearchComponent{
    searchable: String = '';
    professionals: any = {}; 

    constructor(public client: Http){
    }

    getProfessionals() {
        return this.client.get('professionals')
              .subscribe(data => 
                    {
                      this.professionals = data.json();
                      console.log(this.professionals);
                    })
    }
    doSearch(ev: any) {
        let val = ev.target.value;
        if(val.length > 3) {
            this.getProfessionals();
        }
    }
Stephen R. Smith
  • 3,310
  • 1
  • 25
  • 41