问题
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