Reading data.json with HttpClient on Stackblitz?

拜拜、爱过 提交于 2019-12-02 05:07:48

问题


I have a tiny demo and it attempts to read app/data.json using the Angular HttpClient.

const post$:Observable<Post> = <Observable<Post>> http.get('./data.json');

However the HttpClient reponse says:

Failure during parsing ...

Thoughts?


回答1:


Stackblitz currently doesn't serve static files except the case when they are in assets folder.

So you have two options here:

1) Import json directly as module

import data from './data.json';

console.log(data) // => {title: "Simulating HTTP Requsts", content: "This is off the hook!!"}

For more details See other answers

2) Move that json in assets folder(Note: you have to reload stackblitz to make it working):

http.get('/assets/data.json')

Forked Stackblitz




回答2:


Currently, you can't get the JSON directly over HTTP, but you can import it instead

data.json

it returns resource of index.html instead of the data you expected


online example

import { of } from 'rxjs';
import data from './data.json';

export class AppComponent  {
  constructor(http:HttpClient) {

  }

  ngOnInit(){
    const post$ = of(data);
    post$.subscribe(console.log);
  }
}



回答3:


i think there are some issues about reading local json in stackblitz it doesn't return plain json just the index.html instead. but another way is mocking a request from local json, you can try:

import data from './data.json'

ngOnInit(){
  this.getDatas().subscribe(data=>{
    console.log(data)
  })
}

getDatas():Observable<any>{
  return of(data).pipe(delay(1000));
}

forked DEMO



来源:https://stackoverflow.com/questions/54049933/reading-data-json-with-httpclient-on-stackblitz

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!