一、在app.module.ts模块中,注入JsonpModule模块
import {JsonpModule} from "@angular/http";
@NgModule({
imports: [
JsonpModule //注入JSonpModule模块
]
})
二、创建服务httpService,并注入jsonp和map(分装好的服务 可以直接调用)
import {Injectable} from '@angular/core';
import {Jsonp, URLSearchParams} from "@angular/http";
@Injectable()
export class HttpService {
private jsonpTimes = 0; // 用于记录jsonp请求的次数
constructor(private jsonp: Jsonp) {
}
jsonpGet(apiURL, req){
let params = new URLSearchParams();
//设置参数
for (let key in req) {
params.set(key, req[key]);
}
params.set('format', 'json');
params.set("callback", `__ng_jsonp__.__req${this.jsonpTimes}.finished`);
this.jsonpTimes++;
let request = this.jsonp.get(apiURL, { search: params })
.map((res) => {
let response = res.json();
return response;
});
return request;
}
}
三、业务组件调用httpService
let newUrl = localServer + "/search"; //查询网址
let req = { id: 123, name: "abc" }; //查询参数
this.httpService.jsonpGet(newUrl, req).subscribe(data => { let result = data.data; });
后端JAVA代码
@RequestMapping(value = "mergeJson") public void exchangeJson(HttpServletRequest request,HttpServletResponse response) throws Exception { String businessnum = request.getParameter("businessnum"); String paths = request.getParameter("paths"); List<String> pathList = Arrays.asList( paths.split(",")); List<String> resultPath = mergeService.merge(businessnum, pathList); String return_JSONP = String.join(",", resultPath); String jsonCallback = request.getParameter("callback"); //jsonpCallback 客户端请求参数 Map<String,Object> map = new HashMap<>(); map.put("data",return_JSONP); JSONObject resultJSON = new JSONObject(map);//根据需要拼装json PrintWriter pw = response.getWriter(); pw.write(jsonCallback+"("+resultJSON+")"); pw.close(); pw = null; }
参考资料:https://www.cnblogs.com/minigrasshopper/p/7692368.html