2

I'm trying to use map operator from RxJS but it throws an error saying

Property 'map' does not exist on type 'Observable'.

Here is the code

    import { Injectable } from "@angular/core";
    import { Http } from "@angular/http";
    import "rxjs/add/operator/map";
    @Injectable()

    export class DataService {
     constructor(public http: Http) {}

     getData() {
       return this.http
        .get("https://jsonplaceholder.typicode.com/users")
        .map(res => res.json());
      }
    }
2
  • which angular version do you use? Commented Aug 18, 2018 at 5:51
  • @ninjadev1030 Angular 6.0.9 Commented Aug 18, 2018 at 6:38

3 Answers 3

9

For first Http is deprecated in higher versions than Angular 4. Instead of it you need to use HttpClient with HttpClientModule from "@angular/common/http". And using HttpClient you will get the JSON parsed result, so you don't need res.json() longer.

For second map in new verions of RxJS is being used another way. It is now pipeable, you need to use it combined with pipe.

import { Injectable } from "@angular/core";
import { HttpClient} from "@angular/common/http";

@Injectable()    
export class DataService {
  constructor(public httpClient: HttpClient) {}

  getData() {
    return this.httpClient
               .get("https://jsonplaceholder.typicode.com/users")
  }
}

Using map operator

import { map } from 'rxjs/operators';

...

someFunction() {
   this.httpClient.get("https://jsonplaceholder.typicode.com/users")
                  .pipe(map(res) => something with res);
}

...
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. Plus i had to import 'HttpClientModule' instead of only 'HttpModule' in "app.module.ts". And now its working good :)
@Rocktim Thanks. About HttpClientModule I have mentioned it above )
Thanks a lot. I was importing map operator like import 'rxjs/add/operator/map'; this. instead of import { map } from 'rxjs/operators';
5

in RXJS 6 import { map } from 'rxjs/operators';

import { map } from 'rxjs/operators';
getData() {
   return this.http.get("https://jsonplaceholder.typicode.com/users")
   .pipe(
        map(res => res.json())
    );
}

Comments

2
import { Injectable } from "@angular/core";
import { map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
@Injectable()

export class DataService {
 constructor(private http: HttpClient) {}

 getData() {
   return this.http
    .get("https://jsonplaceholder.typicode.com/users")
    .map(res => res.json());
  }
}

1 Comment

This still won't work if using newer versions of RXJS, and also if using HttpClient then there is no need for res.json() anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.