Angular 2服务http post不起作用

Evg*_*tin 0 node.js angular

我有nodejs服务器监听和等待发布请求http://localhost:3000/api/updateLocation 服务器使用PostMan进行JSON post请求测试,一切正常,nodejs输出'Got data'到控制台.但是Angular2似乎并没有将数据发送到服务器.截图PostMan

有什么问题?

NodeJS server.js:

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

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);
  }

}
Run Code Online (Sandbox Code Playgroud)

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 });
  }
}
Run Code Online (Sandbox Code Playgroud)

And*_*dos 5

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

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

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