Andrej Tihonov Andrej Tihonov - 9 months ago 60
Node.js Question

Can not get data from node.js server with angular 2

I am learning angular 2 and I am trying to get data from a node server with the help of the services in angular 2.

So I have an angular component with a button. After I click to this button, an angular service should do a request to the server and fetch the response into a variable. But my variable stays always undefined.

Here is the code of the service:

import { Observable } from 'rxjs/Rx';

// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';


@Injectable()
export class LoginService {


constructor (private http: Http) {

}
private dataUrl = 'http://localhost:1337';

getData() : Observable<Data[]> {
return this.http.get(this.dataUrl)
.map((res:Response) => res.json());
//.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
}


Here is the node.js code:

var http = require('http');
var port = 1337;
var data = "Hi";

http.createServer(function(req, res) {
res.writeHead(200, {"Content-Type": "text/plain"});
res.write(data);
res.end("Hi");
}).listen(port);

console.log('Server running on port %s', port);


Here is the code of my home-page:

import { NavController } from 'ionic-angular';
import { Data } from '../../data/data.component';
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { LoginService } from '../../services/login/login.service';


@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public data: string;

constructor(
private loginService: LoginService
){}

getData() {
this.data = this.loginService.getData()[0].data;
console.log(this.data);
}
}


I also declare the LoginService in the providers array in @NgModule.
My Data component is very simple:

export class Data {
constructor(
public data: string){}
}


Besides that, I use Ionic 2, but I do not think, this would cause the mistake.

Hope guys, u could help me.
Cheers,

Andrej

Answer Source

Since the getData() method from your LoginService returns an Observable (which is async) you need to subscribe to it to get the response

import { NavController } from 'ionic-angular';
import { Data } from '../../data/data.component';
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { LoginService } from '../../services/login/login.service';


@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  public data: string;

  constructor(
      private loginService: LoginService
  ){}

  getData() {

    this.loginService.getData().subscribe((dataFromServer) => {
      // Now you can use the data
      console.log(dataFromServer);
    });
  }
}