DevHelp
DevHelp

Reputation: 305

Nodejs api call from angular2 service

I have node api that returns data to browser using this api :

app.get('/api/patients',function(req,res){
    Patient.getPatients(function(err,patients){
        if(err){
            throw err;
        }
        console.log(patients.length);
        res.json(patients);

    });
});

I am trying to call this api from the service class.

import { Injectable } from '@angular/core';
import { Patient } from '../patient.interface';



@Injectable()
export class PatientDataService {

    patients : Patient[] =[];


    constructor() { }



    getAllPatients(): Patient[]
    {
          // What to do here ??
    }

}

How do i return data from node api to service ?

Upvotes: 1

Views: 1583

Answers (2)

Ben
Ben

Reputation: 2706

You can first import the Angular2 Http library into your service:

import { Http } from '@angular/http';

I also import rx/js for use of Observables and mapping.

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

You can then inject the library into your service:

constructor(private _http: Http) { }

Make your http call to your node.js server like this:

getAllPatients(): Patient[]
{
      // What to do here ??
      return this._http.get('/api/patients')
           .map(this.extractData)
           .catch(this.handleError);
}

For more information, documentation, and clarification please read the Angular 2 Http Docs

Upvotes: 2

Rahul Kumar
Rahul Kumar

Reputation: 5229

Use this

@Injectable()
export class PatientDataService {

    patients : Patient[] =[];


    constructor(private http:Http) { }


        getAllPatients()
         {
          return this.http.get('base_url/api/people').map((res)=>res.json());

        }

}

and in your component inject this service and call

this.patientService.getAllPatients().subscribe((data)=>{
   //data is your patient list
})

Upvotes: 2

Related Questions