一、在app.module.ts模塊中,註入JsonpModule模塊 二、創建服務httpService,並註入jsonp和map(分裝好的服務 可以直接調用) 三、業務組件調用httpService let newUrl = localServer + "/search"; //查詢網址 let ...
一、在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