Angular 2服务http post不起作用

时间:2016-07-23 17:26:25

标签: node.js angular

我有nodejs服务器监听&等待帖子请求http://localhost:3000/api/updateLocation 服务器使用PostMan进行JSON后期请求测试,一切正常,nodejs输出“获得数据”。控制台。但Angular2似乎并没有向服务器发送数据。Screenshot PostMan

问题是什么?

NodeJS server.js:

api.post('/updateLocation', function(req, res){
  //res.send(req.body);
  console.log('Got data');
});

Ionic 2 home.ts:

import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {Service} from '../../service';

@Component({
  templateUrl: 'build/pages/home/home.html',
  providers: [Service]
})
export class HomePage {
  constructor(private navCtrl: NavController, service: Service) {
    setInterval( ()=> {
      service.sendLocation({ x: '46.303344', y: '28.655268' });
    }, 1000);
  }

}

service.ts:

import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';

@Injectable()
export class Service {
  http : any;
  url : string = 'http://localhost:3000/api/updateLocation';
  constructor(http: Http){
    this.http = http;
  }

  sendLocation(location){
    let body = JSON.stringify(location);
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post(this.url, body, { headers });
  }
}

2 个答案:

答案 0 :(得分:5)

您需要订阅http操作,否则请求实际上不会被触发。在使用它之前它仍然是“冷的”。

如果您的api返回json响应,这将起作用,例如:

this.http.post(this.url, body, { headers }).subscribe(
        data => {
            console.log(data.json());           
        }
);

答案 1 :(得分:0)

问题解决了:

1)导入Rxjs / Rx

2)将标题更改为urlencoded

3)将函数sendLocation修改为this(添加了subscribe()方法):

  sendLocation(location){
    let body = JSON.stringify(location);
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    this.http.post(this.url, body, {headers: headers}).subscribe();
  }