【问题标题】:Nodejs api call from angular2 service来自 angular2 服务的 Nodejs api 调用
【发布时间】:2017-08-25 21:39:21
【问题描述】:

我有节点 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 返回到服务?

【问题讨论】:

  • 我认为上面的代码来自angular2
  • @PankajParkar 这是 Angular 2 应用程序,而不是 AngularJS (1) 应用程序。
  • $http 和相关的东西(但 AngularJS 1)here
  • 我的错.. 没有查看 Angular 2 标签.. 虽然它与http.get 相同

标签: node.js angular


【解决方案1】:

使用这个

@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
})

【讨论】:

  • 谢谢 .. 这有帮助,但现在我在浏览器控制台中收到以下错误:XMLHttpRequest cannot load localhost:3000/api/patients。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin 'localhost:4200'。
  • 我通过在节点 api 中添加 CORS 来修复它: app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); });
  • @DevHelp,您正在从一个域上的 AngularJS 应用程序调用另一个域上的 Web 服务器。您是否在 Web 服务器上正确配置了 CORS?
  • @DevHelp,没关系 - 你打败了我 :) 在任何使用“*”的生产应用程序中都要小心,这意味着任何域上的任何应用程序都可以调用你的网络服务器。
  • 谢谢本。如何确保只允许某些域访问此服务?
【解决方案2】:

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

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

我还导入 rx/js 以使用 Observables 和映射。

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

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

constructor(private _http: Http) { }

像这样对 node.js 服务器进行 http 调用:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    相关资源
    最近更新 更多