本文介绍了RsJX“地图"运算符在Angular 6中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用RxJS中的map
运算符,但会引发错误提示
I'm trying to use map
operator from RxJS but it throws an error saying
这是代码
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“地图"运算符在Angular 6中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!