0

I'm following this tutorial: https://www.youtube.com/watch?v=KhzGSHNhnbI&t=527s

And at 51:41 he uses map. But my code doesn't work. Why I can't use it? I get

Property map does not exists on Observable <Response>

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

@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor(public http:Http) { 
    console.log("Data service connected...");
  }

  getPosts() {
    this.http.get('https://jsonplaceholder.typicode.com/posts').map(res => res.json());
  }
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • `http.get()` returns a promise. Try `http.get().then((data) => res.json(data))` – marekful May 11 '18 at 10:46
  • i ge tthe same error but with `then` and res doesn't exist –  May 11 '18 at 10:48
  • gotta love this tutorials where nobody knows the answers –  May 11 '18 at 10:57
  • This should work. What version of angular are you using? It seems that in the newer ones they changed map import statement (https://stackoverflow.com/a/47096060/2610466). – Krypt1 May 11 '18 at 11:00
  • i did exactly what he said npm install -g @angular/cli –  May 11 '18 at 11:02
  • Angular CLI: 6.0.1 Node: 8.9.4 OS: win32 x64 –  May 11 '18 at 11:03
  • You have version 6.0, while tutorial is on the version 4.0. They changed somethings around, and you can't use by default the observable operators by chaining them. Take a look here: https://stackoverflow.com/questions/49811177/angular-6-rxjs-import-syntax – Krypt1 May 11 '18 at 11:05

1 Answers1

1

Service code you provide is using angular 6 which has dependency of rxjs 6.

So from rxjs 6 onwards you have to use pipeable operators and import paths are modified. so please change the code as follows

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor(public http:HttpClient) { 
    console.log("Data service connected...");
  }

  getPosts() {
    this.http
      .get('https://jsonplaceholder.typicode.com/posts')
      .pipe(
        map(res => res.json())
       );
  }
}

And one more recommendation please start using HttpClient Module instead of Http Module. So even you dont need to use map to get json response

Please check this link for httpClient Module

Abinesh Devadas
  • 1,517
  • 13
  • 15