Evgheny Kalkutin Evgheny Kalkutin - 4 months ago 75
Node.js Question

Angular 2 service http post doesnt work

I have nodejs server listening & waiting for post requests

http://localhost:3000/api/updateLocation

Server is tested with PostMan for JSON post request and all is working, nodejs outputs 'Got data' to console. But Angular2 doesnt seems to send data to server.Screenshot PostMan

Whats the problem?

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

Answer

You need to subscribe to the http action, otherwise the request isn't actually fired. It remains 'cold' until it's used.

This would work, if your api was returning a json response, for example:

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