javascript - 不能使用简单的 map ?

标签 javascript angular

我正在关注本教程:https://www.youtube.com/watch?v=KhzGSHNhnbI&t=527s

在 51:41 他使用了 map 。但我的代码不起作用。为什么我不能使用它?我明白了

Property map does not exists on Observable <Response>

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor(public http:Http) { 
    console.log("Data service connected...");
  }

  getPosts() {
    this.http.get('https://jsonplaceholder.typicode.com/posts').map(res => res.json());
  }
}

最佳答案

您提供的服务代码使用 Angular 6,它依赖于 rxjs 6。

因此,从 rxjs 6 开始,您必须使用可管道运算符,并修改导入路径。所以请更改代码如下

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor(public http:HttpClient) { 
    console.log("Data service connected...");
  }

  getPosts() {
    this.http
      .get('https://jsonplaceholder.typicode.com/posts')
      .pipe(
        map(res => res.json())
       );
  }
}

还有一个建议,请开始使用 HttpClient 模块而不是 Http 模块。所以即使你不需要使用map来获取json响应

请检查此link对于httpClient模块

关于javascript - 不能使用简单的 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50290560/

相关文章:

javascript - 已发送回复 1 个回复迟到

angular - 无法在我的 angular-cli 项目上运行 ng lint

javascript - 使用 jQuery 将 HTML 页面动态加载到 div 中

javascript - 动态更改 css 中边框的半径

javascript - Google Firebase OrderByChild 不支持嵌套动态键

angular - 部署的应用程序引擎未对我的内容进行 gzip 压缩

javascript - 如何使用javascript计算两个时间戳之间的差异

node.js - Bcrypt 3.0.1 无法在 Node v 8.12.0 上安装

javascript - 将百度 map 拟合到多个标记,如谷歌地图 fitBounds

javascript - 简化 Javascript 中的 promise