简体   繁体   中英

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 ?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM