angular2 Injectable http ng2使用服务(Injectable)加载(http)数据

发布时间:2019-06-05 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了angular2 Injectable http ng2使用服务(Injectable)加载(http)数据脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

ng2依赖注入,服务中使用http获取服务器数据

1、 定义服务

import {Injectable} From "@Angular/core";
import {Http, Jsonp} from "@angular/http";
import "RxJS/add/@R_406_1162@tor/map";
@Injectable()
export class AppServer {
  constructor(public http:Http, public jsonp:Jsonp) {

  }
  // http.get
  httpGet(url, params) {
    return this.http.get(url, {search: params}).map(result=>result.json());
  }
  // http.post
  httpPost(url, params) {
    return this.http.post(url, params).map(result=>result.json());
  }
  // jsonp
  jsonpGet(url, params) {
    return this.jsonp.get(url, {search: params}).map(result=>result.json());
  }
}

2、 定义组件, 加载服务