Angular2 - http.post(...).map is not a function

32 浏览
0 Comments

Angular2 - http.post(...).map is not a function

我查阅了所有的GitHub问题和StackOverflow帖子,但是我无法使其工作。

(https://github.com/angular/angular/issues/5632)

(https://stackoverflow.com/questions/34515173/angular-2-http-get-with-typescript-error-http-get-map-is-not-a-function-in)

  • 我正在使用Angular2@2.0.0-beta.1版本
  • 当我在控制台中检查时,Rxjs (rxjs@5.0.0-beta.1)已成功导入。

我尝试了不同的导入方式:

import 'rxjs/add/operator/map';

import 'rxjs/rx';

但是我一直收到错误信息:

http.post(...).map is not a function

更新 - 代码上下文

let body = "email=" + email + "&password=" + password;
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-from-urlencoded');
this.http.post('http://angular.app/api/v1/auth') // angular.app是laravel后端
      .map( (responseData) => {
          return responseData.json();
      })

0
0 Comments

Angular2中的http.post()方法返回的是一个Observable对象,而在这个例子中,调用了map()方法来对返回的数据进行处理。但是在这个例子中,报错说map()方法不是一个函数。解决这个问题的方法是引入rxjs库中的Rx对象,即import 'rxjs/Rx'。

整理成一篇文章如下:

在Angular2中,当我们使用http.post()方法发送请求时,返回的是一个Observable对象。我们可以通过调用map()方法来对返回的数据进行处理。然而,在某些情况下,当我们尝试调用map()方法时,会报错说map()不是一个函数。

为了解决这个问题,我们需要引入rxjs库中的Rx对象。具体的解决方法是在代码开头加入import 'rxjs/Rx'语句。这样就可以正确地调用map()方法了。

下面是一个具体的例子:

import {Component} from 'angular2/core';
import {Http} from 'angular2/http';
import 'rxjs/Rx';
@Component({
  selector: 'my-app',
  template: `
    

{{title}}

Test result {{result | json}}

` }) export class App implements OnInit{ public title = 'my title'; public result : String; constructor(private _http : Http) { _http.post('http://jsonplaceholder.typicode.com/posts') .map(res => res.json()) .subscribe( data => this.result = data, err => console.log('ERROR!!!'), () => console.log('Got response from API', this.result) ); } }

希望这个解决方法对你有所帮助。如果你遇到了类似的问题,可以尝试引入rxjs库中的Rx对象来解决。你也可以参考这个例子的Plunker链接:http://plnkr.co/edit/vise2zYxZUmr1kW65mNY?p=preview

0
0 Comments

Angular2 - http.post(...).map is not a function这个问题的出现的原因是Angular2 beta.1需要RxJS 5.0.0-beta.0版本,但是在package.json文件中的依赖项中并未指定这个版本。解决方法是在bootstrap函数的第二个参数中添加HTTP_PROVIDERS,并且在代码中导入'rxjs/Rx'。不过有些用户尝试了这些方法后仍然无法解决问题,可能需要在stackoverflow上寻找其他解决方法。

0