简体   繁体   English

如何在angular-2中进行服务器api调用?

[英]how to make a server api call in angular-2?

I am new to angular2. 我是angular2的新手。 i want to make server call to get the data from my server. 我想进行服务器调用以从服务器获取数据。 actually i know how to do this in angular1.x , but I am not able to find out how it can be done in angular-2. 实际上我知道如何在angular1.x中执行此操作,但是我无法找出如何在angular-2中执行此操作。

This is how I tried in angular1.x 这就是我在angular1.x中尝试过的方式

controller: 控制器:

var pageId = 0;
$scope.getProducts = function () {
    NewProducts.query({
      pageId: pageId,
      activeFilter: 1
    }).$promise.then(function (res) {
      $scope.products= res;
      pageId++;
    }).catch(function (err) {
      console.log('Error happened : ' + JSON.stringify(err));
    });
  };

service: 服务:

.constant('API_HOST', 'http://www.myproductssite.com')
.factory('NewProducts', function ($resource, API_HOST) {
  return $resource(API_HOST + '/prods/page/:pageId/:activeFilter', {
    pageId: '@pageId',
    activeFilter: '@activeFilter'
  }, {
    'query': {
      method: 'GET',
      isArray: true,
      timeout: 20000
    }
  } );
})

html html

<div ng-init="getProducts();">
Res->{{products | json}}
</div>

this is how i build an angular1.x app to make server call using $resource Get method. 这就是我构建一个angular1.x应用程序以使用$ resource Get方法进行服务器调用的方式。 i have no idea how to do this in angular-2. 我不知道如何在angular-2中执行此操作。 is there any ways to do this in angular-2. 在angular-2中有什么方法可以做到这一点。 please help me on how to do this? 请帮助我该怎么做? THANKS. 谢谢。

AJAX calls in Angular are done using the Http service, like so: Angular中的AJAX调用是使用Http服务完成的,如下所示:

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

// ... code ...
let memberInfo;
http.get(url)
    .map(x => x.json()).
    subscribe(result => this.memberInfo = result);

This performs an async HTTP GET call that puts the return value in the memberInfo variable. 这将执行一个异步HTTP GET调用,该调用将返回值放入memberInfo变量中。

For best practice create a new file (service). 为了获得最佳实践,请创建一个新文件(服务)。 and do as follows. 并执行以下操作。

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

@Injectable()
export class Api{

constructor(private http: Http){}
  request(){
     return this.http.get(baseUrl);
   }
}

Inside your component you do this. 在组件内部,您可以执行此操作。

this.service.request().subscribe((res)=>{
  console.log('response',res');
},(err)=>{
 console.log(err)
}
)

reference link 参考链接

In angular2, you can use Http service, like: 在angular2中,您可以使用Http服务,例如:

// inject get instance of Http service.
http.post(API_HOST + '/prods/page/' + pageId + '/' + activeFilter', {
  'query': {
    method: 'GET',
    isArray: true,
    timeout: 20000
  }
} ).subscribe((result) => {
   // handle result
})

I personally prefer to make a common call service. 我个人更喜欢拨打普通电话。 From any component, I will just call this getCall method by passing the params. 从任何组件,我都将通过传递参数来调用此getCall方法。

  public getCall(baseUrl:string, url:string, queryParams ?:any) {
    let _url = baseUrl + url;
    if (queryParams) {
      _url = this.appendQueryParams(_url, queryParams);
    }
    let options = new RequestOptions({
      headers: new Headers();
    });
    return this._http.get(_url, options);
  }



 public appendQueryParams(url:string, queryParams:any) {
     let queryParamString:string = "";
     _.forEach(queryParams, function (value, key) {
        queryParamString += key.trim() + "=" + value + "&";
     });
     queryParamString = queryParamString.slice(0, -1);
     queryParamString = encodeURI(queryParamString);
     url += "?" + queryParamString;
     return url;
}

In Service: 服务中:

  getProducts(queryParams){
    return this._callService.getCall("http://www.myproductssite.com",'/prods/page/'+pageId+'/'+activeFilter, queryParams).map(res => res.json());
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM