RsJX 'Map' operator is not working in Angular 6

∥☆過路亽.° 提交于 2019-12-13 18:15:47

问题


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());
      }
    }

回答1:


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);
}

...



回答2:


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())
    );
}



回答3:


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());
  }
}


来源:https://stackoverflow.com/questions/51905697/rsjx-map-operator-is-not-working-in-angular-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!