从服务内部获取Url的Json

时间:2017-03-18 11:34:25

标签: javascript angular typescript

我的功能无法解决问题。

在我向您提供有关该问题的更多详细信息之前,请让我解释它是如何工作的。单击提交按钮后,我调用我的函数''sendItineraryRequestUrl()''这个函数将从URL获取一个Json然后我将该Json对象传递给函数''drawItineraryOnMap(jsonItineraryResponse:any)''女巫绘制行程在地图上。

CASE1: 在第一种情况下我的代码工作,我能够获得JSON对象,然后在地图上绘制行程。 在我的组件类中:

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函数。

先谢谢你们给我的任何帮助!

1 个答案:

答案 0 :(得分:0)

我最终使用angular 2 http服务来解决问题。 谢谢Sasxa的帮助!

如果有人需要,我可以进行全面修改。

sendItineraryRequestUrl() {
 this.itineraryRequestService.get(this.planRequest)
  .subscribe(plan => this.drawOnMap(plan, this.routeGroup),
    error => console.error(error));
}