1

I have an api method which works and returns an int type. I am trying to convert get response to angular number: enter image description here

This is what I am doing now:
Request to api:

  GetNumberOfPages(topValue: number, companyNamePattern: string) {
    return this.http.get<number>(apiUrl + '/getNumberOfPages?topValue=' + topValue +
      '&companyNamePattern=' + companyNamePattern, httpOptions)
      .pipe(
        tap(v => console.log('GetNumberOfPages complete')),
        catchError(this.handleError('GetNumberOfPages', []))
      );
  }

usage in component:

  getNumberOfPages(topValue, companyNamePattern) {
    var numberOfPagesAny: any;
    this.api.GetNumberOfPages(topValue, companyNamePattern).subscribe(n => numberOfPagesAny = n);
    this.numberOfPages = parseInt(numberOfPagesAny, 10);

    console.log(this.numberOfPages + " number")
    console.log(numberOfPagesAny + " any")

  }

But whatever I try I can't get the value: enter image description here
So how to convert get response to number?

Storm
  • 557
  • 1
  • 8
  • 25
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Heretic Monkey Apr 16 '19 at 14:39
  • Try: `this.api.GetNumberOfPages(topValue, companyNamePattern).subscribe(n => {if(n){ numberOfPagesAny = n}});` – Prashant Pimpale Apr 16 '19 at 14:39
  • try to use the console.log here to see if there any data come back from the api ```this.api.GetNumberOfPages(topValue, companyNamePattern).subscribe(n => console.log(n))``` –  Apr 16 '19 at 14:39
  • You're using `numberOfPagesAny` before it is set. See how `GetNumberOfPages complete` is logged after `NaN number`? – Heretic Monkey Apr 16 '19 at 14:41
  • @HereticMonkey Yes, So how should I fix this? I've also tried it with ```finalize``` but result is the same – Storm Apr 16 '19 at 14:46
  • The ways around the issue are all in the duplicate. You have to put your code in the function passed to `subscribe`. – Heretic Monkey Apr 16 '19 at 14:48
  • Add `responseType: 'text'` to ur httpOptions and remove `` from the get call – Sameh Awad Apr 16 '19 at 15:11

1 Answers1

-1

When you are using Observable, you make asynchronous call. Subscribe is called only when you get the answer back.

Which mean that your console.log() are processed before you enter the subscribe !

So you do get the number of page, you should add a console.log in your subscribe if you want to check it :

this.api.GetNumberOfPages(topValue, companyNamePattern).subscribe(n => { numberOfPagesAny = n, console.log("Number of page"+numberOfPagesAny);});

See : https://angular.io/guide/observables#observables

You need to put your process in the subscribe, or use a callback function.

JuNi
  • 24
  • 3