このフレームワークを使用している私の最初のプロジェクトに取り組んでいる角度/ JavaScriptのアマチュアここです。私は与えられたURLにGET要求を実行するサービスを使用するコンポーネントを持っています。HTTP JSONレスポンスのテキストをトリミングする
コンポーネント:
@Component({
selector: 'jive-list',
templateUrl: './jivelist.component.html',
styleUrls: ['./jivelist.component.css']
})
export class JiveListComponent implements OnInit {
JiveLists: String[]; //placeholder
constructor(private JiveListService: JiveListService) { }
getJiveList(): void {
console.log("test");
this.JiveListService.getData().subscribe(
data => console.log(JSON.stringify(data)));
}
ngOnInit() {
this.getJiveList();
//console.log(this.JiveLists) //placeholder
}
}
サービス:
@Injectable()
export class JiveListService {
API_URL = environment.JIVEAPIURL //can append endpoints where needed
constructor (public http: HttpClient) {
console.log("constructor runs");
}
getData(): Observable<any> {
return this.http.get<any>(this.API_URL).map((res) => res);
}
}
APIのURLは './assets/data/data.json'
これにあり、今のローカルファイルでありますコードは基本的にURLからJSONを取得し、コンソールに記録します。ファイルが純粋にJSONの場合、これは問題なく動作します。ただし、プロダクションで提供されるJSONは常に文字列で始まります。
JSONサンプル:
throw 'allowIllegalResourceCall is false.';
{
"id" : "123456",
"resources" : {
//rest of the JSON
私は2つのソリューションがin this articleをお勧めしようとしているが、それらのどれも私の結果を変えませんでした。
例(未遂)ソリューション:
getData(): Observable<any> {
return this.http.get<any>(this.API_URL).map((res) => res.substring(res.indexOf('{')));
}
マイエラーメッセージ:
SyntaxError: Unexpected token h in JSON at position 1 at Object.parse (<anonymous>) at XMLHttpRequest.onLoad (http://localhost:4200/vendor.bundle.js:43048:37) at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.bundle.js:2513:31) at Object.onInvokeTask (http://localhost:4200/vendor.bundle.js:75481:33) at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.bundle.js:2512:36) at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (http://localhost:4200/polyfills.bundle.js:2280:47) at ZoneTask.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.bundle.js:2587:34) at invokeTask (http://localhost:4200/polyfills.bundle.js:3628:14) at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.bundle.js:3654:17)
私はこの問題を解決する助けとなる任意のアイデアをいただければ幸いです。私はAngular 4.2.4を使用しており、@ Angular/common/HttpClientModuleをHTTPハンドラとして使用しています。
あなたは何かを明らかにするためにあなたのjsonサンプル全体を投稿できます – amal
このres.toString()のようなものを試してみてください。私はそれがjavascriptオブジェクトとあなたの2つの関数indexOfとこの理由のために働いていない部分文字列で動作しようとしたと思う – qchap
@qchap toString()と同じエラーが追加されました – ividito