RsJX“地图"运算符在Angular 6中不起作用 [英] RsJX 'Map' operator is not working in Angular 6

查看:94
本文介绍了RsJX“地图"运算符在Angular 6中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用RxJS中的map运算符,但会引发错误提示

I'm trying to use map operator from RxJS but it throws an error saying

可观察"类型不存在属性地图".

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“地图"运算符在Angular 6中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆