我的函数有问题,无法通过服务运行。
在我给你更多关于这个问题的细节之前,让我解释一下它是如何工作的。单击提交按钮后,我调用函数“sendItineraryRequestUrl()”,此函数将从 URL 获取 Json,然后我将该 Json 对象传递给函数“drawItineraryOnMap(jsonItineraryResponse: any)”,女巫绘制行程在 map 上。
案例 1: 在第一种情况下,我的代码有效,我能够获取 JSON 对象,然后在 map 上绘制行程。 在我的组件类中:
sendItineraryRequestUrl() {
var getJSONResponse = (url: any, callback: any) => {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = () => {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
getJSONResponse('MYSERVERURL',
(err: any, jsonData: any) => {
if (err !== null) {
alert('Something went wrong: ' + err);
} else {
this.drawItineraryOnMap(jsonData, this.routeGroup);
}
});
}
drawItineraryOnMap(jsonItineraryResponse: any, layerGroup: any) {
//... my drawing function code
}
CASE2:如果我创建了一个 itierary-request.service.ts 并在其中放置了 sendItineraryRequestUrl() 并将其重命名为 fetchItineraryResponse() 并进行了一些更改: 在这种情况下,我的 itineraryRequestResponse 始终未定义
在我的服务类中:
import {Injectable} from "@angular/core";
@Injectable()
export class ItineraryRequestService {
itineraryRequestResponse: any;
fetchItineraryResponse() : any {
let getJSONResponse = (url: any, callback: any) => {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = () => {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
getJSONResponse('MY SERVER URL',
(err: any, jsonData: any) => {
if (err !== null) {
alert('Something went wrong: ' + err);
} else {
this.itineraryRequestResponse = jsonData;
}
});
return this.itineraryRequestResponse;
}
}
在我的组件类中:
constructor(private geoCodingService: GeoCodingService,
private polylineDecodingService: PolylineDecodingService,
private itineraryRequestService: ItineraryRequestService) {}
sendItineraryRequestUrl() {
let jsonData = this.itineraryRequestService.fetchItineraryResponse();
this.drawItineraryOnMap(jsonData, this.routeGroup);
}
drawItineraryOnMap(jsonItineraryResponse: any, layerGroup: any) {
//... my drawing function code
}
我没有忘记在我的组件提供者中添加我的服务或导入我的服务。 我确定问题出在 Json 函数上。
提前感谢你们能给我的任何帮助!
最佳答案
我最终使用 angular 2 http 服务来解决这个问题。 谢谢 Sasxa 的帮助!
如果有人需要,我可以提供完整的修改。
sendItineraryRequestUrl() {
this.itineraryRequestService.get(this.planRequest)
.subscribe(plan => this.drawOnMap(plan, this.routeGroup),
error => console.error(error));
}
关于javascript - 从服务内部的 Url 获取 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42873839/