从angular2服务调用Nodejs api

我有节点api返回数据到浏览器使用这个api:

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

我想从服务类中调用这个api。

 import { Injectable } from '@angular/core'; import { Patient } from '../patient.interface'; @Injectable() export class PatientDataService { patients : Patient[] =[]; constructor() { } getAllPatients(): Patient[] { // What to do here ?? } } 

我如何从节点API返回数据服务?

用这个

 @Injectable() export class PatientDataService { patients : Patient[] =[]; constructor(private http:Http) { } getAllPatients() { return this.http.get('base_url/api/people').map((res)=>res.json()); } } 

并在你的组件注入这个服务和调用

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

您可以先将Angular2 Http库导入到您的服务中:

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

我也导入rx / js使用Observable和映射。

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

然后,您可以将库注入您的服务:

 constructor(private _http: Http) { } 

使你的http调用你的node.js服务器是这样的:

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

有关更多信息,文档和说明,请阅读Angular 2 Http Docs