【问题标题】:POST form Angular2POST表单Angular2
【发布时间】:2017-10-11 14:27:46
【问题描述】:

我正在尝试使用 Angular2 和 NodeJS API 作为后端服务器来执行登录表单。

我无法向 API 发布任何请求。 这是我前面的代码示例:

private authenticate_url = "Server_URL:PORT/authenticate";
login(username: string, password: string): Observable<User> {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    console.log("Username : "+username+" Password : "+password);
    return this.http.post(this.authenticate_url, { username, password }, options)
                .map(this.extractData)
                .catch(this.handleError)
}

当我检查网络活动时,没有执行任何 POST 请求。

【问题讨论】:

  • 检查你的浏览器 f12,看看它记录了什么。
  • ERROR TypeError: this.http.post(...).map(...).catch 不是函数

标签: node.js rest angular authentication post


【解决方案1】:

你需要使用 RxJS 的 .subscribe() 方法才能真正执行查询,所以你需要这样写:

return this.http.post(this.authenticate_url, { username, password }, options)
                .map(this.extractData)
                .catch(this.handleError)
                .subscribe((queryResult) => {console.log(queryResult)})

或者你可以在你的函数之外这样做:

login("baksdasd", "asfasfasdf").subscribe((queryResult) => {console.log(queryResult)})

您还需要导入您使用的运算符:

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

这里有一个详细的教程来解决您可能遇到的任何其他问题:https://scotch.io/tutorials/angular-2-http-requests-with-observables

【讨论】:

  • 我无法使用订阅功能,因为我使用的是 Observable。在这种情况下,我认为正确的方法是使用“map”而不是“subscribe”。使用您的代码,我遇到了这个错误: /home/iot/ng2-admin/src/app/_services/authentication.service.ts (25,18) 中的错误:“订阅”类型上不存在属性“捕获”。
  • 是的,抱歉,您需要订阅 Observable。所以如果你在你的函数中返回它,你需要订阅任何你想使用它的地方,就像我在第二种情况下展示给你的一样。我将更新我的答案。
  • 我的代码中缺少的是订阅 Observable !我所需要的就是那个。谢谢耶稣博特拉
猜你喜欢
  • 1970-01-01
  • 2016-07-27
  • 2017-08-08
  • 2017-07-09
  • 2017-10-23
  • 2016-05-04
  • 1970-01-01
  • 1970-01-01
  • 2010-09-16
相关资源
最近更新 更多