[Fixed] How to write a Promise as an Observable?

Issue

I am new to Angular and just worked with promises but as far as I know I should use Observables but I have some problems here.

So my code with a promise to do a GET request looks like this:

apiGet(method: any, query: any): Promise<any> {
    return new Promise((resolve, reject) => {
      var otmAPI =
        this.url +
        method +
        "?apikey=" +
        this.API_KEY;
      if (query !== undefined) {
        otmAPI += "&" + query;
      }
      fetch(otmAPI)
        .then(response => response.json())
        .then(data => resolve(data))
        .catch(function(err) {
          console.log("Fetch Error :-S", err);
        });
    });
  }

So far my Observable method looks like this:

getPois(method: any, query: any): Observable<any> {
    return this.http.get(this.url +
      method +
      "?apikey=" +
      this.API_KEY).pipe(
        tap(data => {
          console.log(data)
          if (query !== undefined) {
            data += "&" + query;
          }
        })
      );
  }

I don’t know if I did it correctly but it works, the problem is just I cannot append the query.
For the promise I can append it (the if-block will append the query)
But when I try to do this in the Angular way with a pipe and then tap (to be honest, I don’t know whether to use tap or map or so) but here it doesn’t work! I get a Bad Request.

Would appreciate your help!

Solution

Piping is used when you have to chain multiple observables together.
Looks like you want to add query parameter in the URL based on a condition .
You can do something like this :

getPois(method: any, query: any): Observable<any> {
    let otmAPI = `${this.url}${method}?apikey=${this.API_KEY}`;
    if (query !== undefined) {
      otmAPI += "&" + query;
    }
    return this.http.get(otmAPI);
  }

then in your component subscribe to it :

 this.getPois("method","query").subscribe(res=>{
      console.log('success',res)
    })

Leave a Reply

(*) Required, Your email will not be published