Angular:无法使用 HttpClient 获取本地 json [英] Angular : Unable to GET local json using HttpClient

查看:50
本文介绍了Angular:无法使用 HttpClient 获取本地 json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Angular5 中提供的最新 HttpClient 组件来发出对本地 json 的 get 请求,但此后我收到了 404.我已经在我的 app.module.ts 中导入了 HttpClientModule 模块.

I am using the latest HttpClient component provided in Angular5 to make a get request for local json but I am getting 404 ever since. I have already imported HttpClientModule module in my app.module.ts.

文件夹结构快照:

我正在为 blog-list.json 调用 blog-detail 组件.这是我的代码:

I am making the call from blog-detail component for blog-list.json. Here is my code:

  constructor(private http: HttpClient) {
  }

  ngOnInit(): void {
    // this.http.get('https://jsonplaceholder.typicode.com/posts/1').subscribe((data:Blog[]) => {
    this.http.get('app/api/blog-list.json').subscribe((data:Blog[]) => {
         this.blogs = data;
    });
  }

我收到以下错误:

GET http://localhost:909/app/api/blog-list.json 404 (Not Found)

即使我尝试通过点击 http 直接在浏览器中打开文件://localhost:909/src/app/api/blog-list.json 我在那里提供应用程序而不是 json 文件.

Even if I try to open the file in browser directly by hitting http://localhost:909/src/app/api/blog-list.json I get the application served there instead of the json file.

请注意,对 web 上的 rest api 的注释请求成功,但仅调用本地 json 文件失败.

Please note that the commented request to a rest api on web is successful but fails for call only to a local json file.

推荐答案

我能够解决这个问题,但它最初发生的原因有点奇怪.

I was able to fix this but its kinda weird that why it happened at the first place.

为此,我必须更新 .angular-cli.json 并在 assets 属性中添加 api 文件夹的路径.现在资产属性看起来像:

For this I had to update the .angular-cli.json and add the path to api folder in assets property. Now the assets property looks like:

"assets": [
    "assets",
    "app/api",
    "favicon.ico"
 ]

这篇关于Angular:无法使用 HttpClient 获取本地 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆