Crocsx
Crocsx

Reputation: 7609

How to return an observable from http request

I have the following request in a service in angular 9 :

getUsers(value: string, offset = 0) {
    return this.http.get<GetUsers>(`users`);
  }

This allow me to subscribe and fetch the result in the component, but my service can't fetch the data.

I would like that this function will execute the request, read the response and then return the observable to the component

I tried

  return this.http.get<GetUsers>(`users`)
      .map(res => { 
            //do my stuff
            return res;
      });

but I have >Property 'map' does not exist on type 'Observable

I tried using

.pipe(
      map(res => {
        console.log(res)
        return res;
      })
    );

but it say there is no map did you mean Map ?

Upvotes: 2

Views: 1094

Answers (2)

Hem Sunder
Hem Sunder

Reputation: 36

Make sure to check your package.json if 'rxjs' package exists. If not, install it by entering following command on terminal.

npm install rxjs --save

You just have to import the "map" operator from "rxjs" that comes pre-installed in angular. Just add this line on top of your component file based on Angular version.

import { map } from 'rxjs/operators';

or

import { map } from 'rxjs';

Now it should work fine.

Upvotes: 0

mwilson
mwilson

Reputation: 12900

You are returning the overservable correctly. The reason why you're getting the error for map is probably because you don't have rxjs installed

Try this:

  1. npm install rxjs --save
  2. Add import { map } from 'rxjs/operators'; to your file

Upvotes: 2

Related Questions