ng2服务封装http,jsonp获取后台数据的方法
1、定义服务
import {Injectable} from "@angular/core"; import {Http, Jsonp} from "@angular/http"; import "rxjs/add/operator/map"; @Injectable() export class HttpServer { constructor(public jsonp: Jsonp, public http: Http) { } /* * url: 服务器api接口地址 * params: 传递参数对象 */ // get方法 httpGet(url, params) { return this.http.get(url, {search: params}).map(res=>res.json); } // post方法 httpPost(url, params) { return this.http.post(url, {search: params}).map(res=>res.json); } // 跨域请求 jsonpGet(url, params) { return this.jsonp.get(url, {search: params}).map(res=>res.json()); } }
2、app.module.ts文件中引入服务
import {HttpServer} from "./http.server.ts"; ... providers: [HttpServer] ...
3、组件中使用服务获取数据
... import {URLSearchParams} from "@angular/http"; ... // 使用服务 // 设置参数 var params = new URLSearchParams(); params.set("callback", "JSONP_CALLBACK"); // 调用jsonpGet方法,跨域请求数据 httpServer.jsonpGet("http://localhost:3000/users", params).subscribe(res=> { console.log(res); });
注意
1. 服务需要在constructor(public httpServer: HttpServer)参数中初始化, this.httpServer.httpGet() 2. 服务有两种引入方式,如果在全局引入,那么组件中还要引入文件路径,不用写,providers:[]
相关推荐
fengchao000 2020-06-17
adonislu 2020-05-16
zmosquito 2020-05-10
adonislu 2020-05-10
somebodyoneday 2020-04-22
fengchao000 2020-04-22
fengchao000 2020-04-11
Richardxx 2020-03-07
somebodyoneday 2020-03-06
fengchao000 2020-03-05
somebodyoneday 2020-02-16
xiaouncle 2020-02-13
baijinswpu 2020-01-29
fengchao000 2020-01-10
fengchao000 2019-12-25
newthon 2019-12-23
somebodyoneday 2013-07-11