RsJX 'Map' 运算符在 Angular 6 中不起作用 [英] RsJX 'Map' operator is not working in Angular 6
问题描述
我正在尝试使用 RxJS 中的 map
运算符,但它抛出一个错误说
I'm trying to use map
operator from RxJS but it throws an error saying
'Observable' 类型不存在属性 'map'.
Property 'map' does not exist on type 'Observable'.
这是代码
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());
}
}
推荐答案
首先 Http
在高于 Angular 4 的版本中被弃用.取而代之的是,您需要将 HttpClient
与 "@angular/common/http"
中的 HttpClientModule
一起使用.并且使用 HttpClient
你会得到 JSON 解析结果,所以你不需要 res.json()
更长的时间.
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.
对于 RxJS 新版本中的第二个 map
正在以另一种方式使用.它现在是可管道化的,您需要将它与 pipe
结合使用.
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")
}
}
使用map
操作符
import { map } from 'rxjs/operators';
...
someFunction() {
this.httpClient.get("https://jsonplaceholder.typicode.com/users")
.pipe(map(res) => something with res);
}
...
这篇关于RsJX 'Map' 运算符在 Angular 6 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!