【问题标题】:RsJX 'Map' operator is not working in Angular 6RxJS 'Map' 运算符在 Angular 6 中不起作用
【发布时间】:2019-01-25 02:31:03
【问题描述】:

我正在尝试使用 RxJS 中的 map 运算符,但它会抛出一个错误提示

“可观察”类型上不存在属性“地图”。

这里是代码

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

【问题讨论】:

  • 你使用哪个 Angular 版本?
  • @ninjadev1030 Angular 6.0.9

标签: angular typescript angular6 rxjs6


【解决方案1】:

首先,Http 在高于 Angular 4 的版本中已被弃用。取而代之的是,您需要使用HttpClient"@angular/common/http" 中的HttpClientModule。而使用HttpClient,您将获得JSON 解析结果,因此您不需要更长的res.json()

RxJS 新版本中的第二个 map 正在以另一种方式使用。它现在是可管道的,您需要将它与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);
}

...

【讨论】:

  • 谢谢。另外,我必须在“app.module.ts”中导入“HttpClientModule”,而不仅仅是“HttpModule”。现在它的工作很好:)
  • @Rocktim 谢谢。关于 HttpClientModule 我上面已经提到了)
  • 非常感谢。我正在导入地图运算符,例如 import 'rxjs/add/operator/map';这。而不是 import { map } from 'rxjs/operators';
【解决方案2】:

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

    【讨论】:

    • 如果使用较新版本的 RXJS,这仍然不起作用,如果使用 HttpClient,则无论如何都不需要 res.json()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 2018-10-21
    • 2019-04-28
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多