gpt4 book ai didi

node.js - 来自 angular2 服务的 Nodejs api 调用

转载 作者:太空宇宙 更新时间:2023-11-03 22:51:16 27 4
gpt4 key购买 nike

我有 Node 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 ??
}

}

如何将数据从 Node api 返回到服务?

最佳答案

使用这个

@Injectable()
export class PatientDataService {

patients : Patient[] =[];


constructor(private http:Http) { }


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

}

}

并在您的组件中注入(inject)此服务并调用

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

关于node.js - 来自 angular2 服务的 Nodejs api 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43143677/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com