【发布时间】:2016-05-10 20:07:15
【问题描述】:
我正在尝试调用 JSON 对象。如果我使用 JSON.stringify(data),我可以让它工作,但是当我切换到 JSON.parse(data) 时,我得到一个错误。首先,这是我得到的控制台错误:
EXCEPTION: SyntaxError: Invalid character
EXCEPTION: SyntaxError: Invalid character
STACKTRACE:
SyntaxError: Invalid character
at Anonymous function (eval code:20:42)
at SafeSubscriber.prototype.__tryOrUnsub (eval code:225:13)
at SafeSubscriber.prototype.next (eval code:174:17)
at Subscriber.prototype._next (eval code:124:9)
at Subscriber.prototype.next (eval code:88:13)
at MapSubscriber.prototype._next (eval code:82:9)
at Subscriber.prototype.next (eval code:88:13)
at onLoad (eval code:48:21)
at ZoneDelegate.prototype.invokeTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:354:18)
at onInvokeTask (eval code:36:25)
SCRIPT1014: Invalid character
File: Subscriber.js, Line: 229, Column: 13
这是我的 http-json.service.ts:
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
//next lines are supposed to help...
import 'rxjs/Rx';
import 'rxjs/add/operator/map'; //not sure if needed. for .map below
import { Observable } from 'rxjs/Observable';
@Injectable()
export class HTTPJsonService {
constructor(private http: Http) { }
private jsonUrl = 'http://localhost:57470/escoapi/ActiveOffersByZip/offer-zip/';
getEscos(zipCode: string) {
this.jsonUrl += zipCode;
console.log(this.jsonUrl);
//THIS NEXT LINE IS WHERE IT STOPS. SEEMS TO BE CAUSING THE ERROR.
return this.http.get(this.jsonUrl)
.map(this.extractData);
}
private extractData(res: Response) {
if (res.status < 200 || res.status >= 300) {
throw new Error('Bad response status: ' + res.status);
}
let body = res.json();
return body.data || {};
}
}
我以为我以前可以使用此功能,但奇怪的是现在无法使用。打字稿似乎可以编译。我不确定 .map 是否可能无法正常工作,但我认为我正确地导入了必要的文件(实际上可能导入了超出需要的文件)。
【问题讨论】:
-
你能提供一些jsonUrl的例子吗?
-
你在哪里打电话给
JSON.parse()或JSON.stringify()。返回的 JSON 长什么样子? -
export class HTTPJsonComponent { getData: string; zipCode: string; constructor(private _httpService: HTTPJsonService) { } onTestGet() { this._httpService.getEscos(this.zipCode) .subscribe( data => this.getData = JSON.parse(data), error => alert(error), () => console.log('done') ); } } -
返回的字符串化 JSON 在我看来就像一个普通对象,
[{"SEQ":134770,"SERVICE_ZONE":"NGRID in Zone F"...等
标签: json angular angular2-services