1

I'm trying to implement a test application with Angular. The issue scenario is that I need to do a Get and return a value based on the data gotten from that Get request. See below:

public getNextId(entityName: string): number {
    console.info('Retrieving next ID for  ' + entityName);

    let seqId: SeqId;

    const url = `${this.apiURL}/${entityName}`;

    console.info('SeqID URL: ' + url);

    this.http.get<SeqId>(url)
        .subscribe((data: SeqId) => seqId = data); -> 1

    /*Do something with seqId */ -> 2

    return seqId.nextEntityId;
}

The thing is that (2) executes before (1). When (2) is reached seqId variable hasn't been set yet.

How can I do a Get, process the data retrieved and return something, all in the same method?

Thanks in advance

Felix Lemke
  • 6,189
  • 3
  • 40
  • 67
Rainier Diaz
  • 65
  • 1
  • 4
  • Possible duplicate of [How do I return the response from an Observable/http/async call in angular2?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2) – ConnorsFan Oct 19 '18 at 17:38
  • You have to do the processing inside of the `subscribe` callback. – ConnorsFan Oct 19 '18 at 17:38

1 Answers1

-1

You need to return an observable from here instead of subscribing

  GetData() {return  this.http.get<SeqId>(url)
    .pipe(map(data: SeqId) => seqId = data); 
}

And in the controller, subscribe to this method and do the required operation

mak15
  • 367
  • 2
  • 12