Search code examples
angularhttprxjshttpclientangular-services

.map not accessible from HttpClient


I'm following a tutorial, but it's a little outdated so I'm trying to fill in the pieces. Currently the services looks like


import { Http } from '@angular/http';


export class TodoService {
  constructor(private http: Http) {
  }

  add(todo) {
    return this.http.post('...', todo).map(r => r.json());
  }

  getTodos() {
    return this.http.get('...').map(r => r.json());
  }

  delete(id) {
    return this.http.delete('...').map(r => r.json());
  }
}

but it says Cannot find module '@angular/http' or its corresponding type declarations.ts(2307)

So I changed it to

  constructor(private http: HttpClient) {

but now I get .map red underline with Property 'map' does not exist on type 'Observable<Object>'.ts(2339)

I tried import { map } from "rxjs/operators"; and import 'rxjs/add/operator/map'; but I still get error.

How can I configure this to work without rewriting this.http.post/get/delete line?

I appreciate any help!


Solution

  • map is an rxjs operator, you can use it like this:

    import { map } from "rxjs/operators";
    return this.http.post('...', todo).pipe(
     map(r => r.json())
    );
    

    and whu you are using the deprecated angular/http, you can use HttpClient

    import { HttpClient } from '@angular/common/http';