带有url且没有正文参数的Angular http post方法请求

时间:2017-10-29 20:17:03

标签: angular http-post angular-http

打字稿代码应该调用POST端点。终点只是一个没有身体参数的网址。我通过提供url而没有其他参数尝试了http.post()方法。

示例代码。

let postUrl = "http://hostname:9893/service/fetch/72637"; 

this.http.post(postUrl, {}).map((res:Response) => res.json()).subscribe( data => {
      console.log("post url: "  + data );
});

错误:

core.es5.js:1020 message:"Cannot read property 'post' of undefined" stack:"TypeError: Cannot read property 'post' of undefined\n    at HTMLTableRowElement.<anonymous> (http://localhost:3000/5.chunk.js:222:23)\n    at HTMLTableRowElement.wrapFn [as __zone_symbol___onclick] (http://localhost:3000/polyfills.bundle.js:6601:39)\n    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:3000/polyfills.bundle.js:5969:31)\n    at Object.onInvokeTask (http://localhost:3000/vendor.bundle.js:66347:33)\n    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:3000/polyfills.bundle.js:5968:36)\n    at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (http://localhost:3000/polyfills.bundle.js:5736:47)\n    at HTMLTableRowElement.ZoneTask.invoke (http://localhost:3000/polyfills.bundle.js:6031:38)"
__proto__:Error {constructor: , name: "TypeError", message: "", …} constructor:function TypeError() { … }


更新:
溶液

上面的代码正在回调中使用,因此这个上下文会更新到不同的上下文,因此http不可用。与此绑定解决了这个问题。

2 个答案:

答案 0 :(得分:0)

http应该在构造函数中注入

import {Http} from '@angular/http';

export class Myservice{
  constructor(public http: Http) { }
}

答案 1 :(得分:0)

上面的代码正在回调中使用,因此这个上下文会更新到不同的上下文,因此http不可用。与此绑定解决了这个问题。

相关问题