-1

I would like to form result of http call as result of method. For example:

Code with error:

getPersonId(idBook: number): number {
    return this.mpShipmentWebAPI
        .GetLast({ bookID: idBook })
        .subscribe((books) => {
            return Number(books.Data[0].ID);
        });               
}

I know how to fix the above code:

getPersonId(idBook: number): number {
    return this.mpShipmentWebAPI
        .GetLast({ bookID: idBook })
        .subscribe((books) => {
            this.handleData(books),
        });               
}

What I want is to check result of this in the following manner:

let idPerson = this.getPersonId(idBook);
if (idPerson > 0) {
    //the rest code here
}

Is it possible to do?

StepUp
  • 36,391
  • 15
  • 88
  • 148
  • You can't do that, because the `subscribe` is returning an `Observable` and http calls are `asynchronous`. – Milad Aug 31 '17 at 11:34

1 Answers1

1

It is not possible because http calls are asynchronous. Trying to make them synchronous is not recommended because this will freeze everything else. The correct way will be this:

getPersonId(idBook: number): Observable<number> {
    return this.mpShipmentWebAPI
        .GetLast({ bookID: idBook })
        .map(books => this.handleData(books));               
}

...

this.getPersonId(idBook)
    .filter(idPerson => idPerson > 0)
    .do(idPerson => {
       // rest of your code
    });
Markus Kollers
  • 3,508
  • 1
  • 13
  • 17