1

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

3 Answers 3

2

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);
    });
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Glad to help @DineshKanivu :)
2

You need to call subscribe function to make http call.

getData() {
    this.loginService.getData().subscribe((res) => {
    this.data = res;
    console.log(this.data);
    });

  }

You can find more about http client in angular 2 here.

Comments

1
getData() : Observable<Data[]> {
        return this.http.get(this.dataUrl)     //<<<$$$ returns observable
            .map((res:Response) => res.json());

}

This piece of code returns observable.

So, You need to subscribe to observable in order to get the data as shown below,

getData() {
    this.loginService.getData().subscribe((res)=>{
        this.data=res;
        console.log(this.data);
    })

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.