我正在尝试调用JSON对象。如果我使用JSON.stringify(data),我可以让它工作,但当我切换到JSON.parse(数据)时,我得到一个错误。首先,这是我得到的控制台错误:
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可能无法正常工作,但我认为我正在正确导入必要的文件(实际上可能导入了超过需要的文件)。
答案 0 :(得分:1)
尝试这种方式,首先制作一个界面体
export interface IBody{
body:string;
}
您可以添加任意数量的字段。
并将该接口导入服务类
import {IBody} from 'your_path'
getEscos(zipCode: string):Observable<IBody[]> {
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((res: Response) => {
if (res.status < 200 || res.status >= 300) {
throw new Error('Bad response status: ' + res.status);
}
else{
let body = res.json();
console.log(body.data);
return body.data || {};
}
});
}
通过这种方式,界面将帮助您指出数据是否有任何问题:)。希望它澄清