【问题标题】:Angular 4 404 error - Call json file using http get method angular 4 webpackAngular 4 404 错误 - 使用 http get 方法 angular 4 webpack 调用 json 文件
【发布时间】:2017-12-12 14:17:09
【问题描述】:

我有一个本地 json 文件并试图从 Http get 方法中读取。应用程序在控制台 (404) 上抛出异常。如果您使用 webpack,我已经阅读了资产/数据对于 angular-cli.json 不可用。我正在使用 webpack。你知道将 json 文件放在哪里以便读取吗?

import {IProduct} from './product.model';

@Injectable()
export class ProductService {
    private productUrl = require('./product.json');

    constructor(private _http: HttpClient) { }

    getProducts(): Observable<IProduct[]> {
        return this._http.get<IProduct[]>(this.productUrl)
            .do((data) => console.log('products: ' + JSON.stringify(data)))
            .catch(this.handleError);
    }
}

product.json 位于 ProductService 的同一目录中。

【问题讨论】:

  • 你能分享你的代码吗?
  • 那么您尝试使用的路径是什么,文件在您的结构中的什么位置?
  • 我已经用我正在使用的代码更新了我的帖子

标签: json angular http webpack


【解决方案1】:

使用 webpack,无论您将 json 文件存储在何处,都可以从任何地方访问它,但始终从 src 文件夹开始。

所以它应该看起来像这样:

return this._http.get<IProduct[]>('src/app/services/product.json')

即只需标记从 src 开始的 json 文件的完整路径。

【讨论】:

  • 它不起作用,仍然:找不到模块:错误:无法解析'src/main/webapp/app/layouts/product/products.json'
  • 您是否检查并仔细检查了路径是否正确? :)
  • 如果路径正确,看来你的结构和平时有点不一样,那就试试从webapp/app....开始
【解决方案2】:

如果使用 angular cli


AFAIK 有一种方法可以做到这一点。

  1. 将文件(比如 file.json)保存在 assets 文件夹中。

  2. 在 angular-cli.json 文件中,转到 node:apps> assets 并验证名称“assets”是否存在。

现在访问:

http://localhost:[PORT_NUMBER]/assets/file.json

顺便说一句,您的网络应用程序不应该是您的 api。不要使用 json 文件,而是在您的服务中创建变量。

例子:

import { Injectable } from "@angular/core";

@Injectable()
export class DataMockService {
    public GetObjects(): any {
        return {
            name: "nilay", ...
        };
    }
}

【讨论】:

  • 我没有资产文件夹。资产文件夹仅在您使用 angular-cli.json 文件时可用。我正在使用 webpack。
猜你喜欢
  • 1970-01-01
  • 2018-05-27
  • 1970-01-01
  • 2018-07-18
  • 1970-01-01
  • 2018-05-15
  • 1970-01-01
  • 2018-05-21
  • 2019-01-20
相关资源
最近更新 更多