Javascript Angular4:如何访问本地 json?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43275995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:48:35  来源:igfitidea点击:

Angular4: how do access local json?

javascriptjsonangular

提问by Dan Neciu

In Angular2 you could have a folder /data/ and a json file there and you could access it at localhost:4200/data/something.json.

在 Angular2 中,你可以有一个文件夹 /data/ 和一个 json 文件,你可以在 localhost:4200/data/something.json 访问它。

This is no longer possible in Angular4.

这在 Angular4 中不再可能。

Any ideea how to get it to work?

任何想法如何让它工作?

采纳答案by Pardeep Jain

you can use this code

你可以使用这个代码

@Injectable()
export class AppServices{

    constructor(private http: Http) {
         var obj;
         this.getJSON().subscribe(data => obj=data, error => console.log(error));
    }

    public getJSON(): Observable<any> {
         return this.http.get("./file.json")
                         .map((res:any) => res.json())
                         .catch((error:any) => console.log(error));

     }
}

here file.jsonis your local json file.

file.json是您的本地 json 文件。

see here also

也见这里

also see the changlog of angular-cli for path

另请参阅 angular-cli 的 changlog 路径

回答by Vivek Shukla

Ofcourse its possible. Let's assume here is your json file

enter image description here

当然有可能。让我们假设这是您的 json 文件

在此处输入图片说明


And here is your code to call the json


这是您调用 json 的代码

import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map'

@Injectable()
export class YourService {

   constructor(private http: Http) { }

   getAdvantageData(){
      let apiUrl = './assets/data/api/advantage.json';
      return this.http.get(apiUrl)
      .map( (response: Response) => {
         const data = response.json();
         return data;
      });
   }  
}

回答by Deepak Pathak

I was facing the same issue, where my Observable Angular service was located at inside 'src/app/' folder and it was trying to load a local JSON file. I tried to put the JSON file inside the same app folder, inside a new 'api' folder, used various kinds of relatives/absolute routes, but it didn't help and I got 404 error. The moment I put it inside 'assets' folder, it worked. I guess there is more to it?

我遇到了同样的问题,我的 Observable Angular 服务位于“src/app/”文件夹内,它试图加载本地 JSON 文件。我试图将 JSON 文件放在同一个应用程序文件夹中,在一个新的“api”文件夹中,使用各种亲戚/绝对路由,但它没有帮助,我收到了 404 错误。我把它放在“资产”文件夹中的那一刻,它就起作用了。我想还有更多吗?

Maybe this link helps:

也许这个链接有帮助:

COMPONENT-RELATIVE PATHS IN ANGULAR

Angular 中的组件相关路径

回答by yazantahhan

You can use "require" too;

你也可以使用“require”;

let test = require('./test.json');

回答by Benjamin Caure

Based on this post, here is complete answer for Angular 6+:

基于这篇文章,这里是 Angular 6+ 的完整答案:

From angular-cli doc, json can be considered as assets and accessed from standard import without use of ajax request.

angular-cli doc 中,json 可以被视为资产,可以从标准导入访问,而无需使用 ajax 请求。

Let's suppose you add your json files into "your-json-dir" directory:

假设您将 json 文件添加到“your-json-dir”目录中:

  1. add "your-json-dir" into angular.json file (:

    "assets": [ "src/assets", "src/your-json-dir" ]

  2. allow import of json modules into typings.d.ts file to prevent from typescript errors:

    declare module "*.json" { const value: any; export default value; }

  3. in your controller/service/anything else file, simply import the file by using this relative path:

    import * as myJson from 'your-json-dir/your-json-file.json';

  1. 将“your-json-dir”添加到 angular.json 文件中(:

    "assets": [ "src/assets", "src/your-json-dir" ]

  2. 允许将 json 模块导入到 Typings.d.ts 文件中以防止打字稿错误:

    declare module "*.json" { const value: any; export default value; }

  3. 在您的控制器/服务/任何其他文件中,只需使用此相对路径导入文件:

    import * as myJson from 'your-json-dir/your-json-file.json';

回答by deathrace

You could add your folder location under Assets tag in angular.json

您可以在 angular.json 的 Assets 标签下添加文件夹位置

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

回答by Dan Neciu

I figured it out.

我想到了。

In Angular2 I had the folder under the src folder. In Angular4 you have to have it in the root folder.

在 Angular2 中,我有 src 文件夹下的文件夹。在 Angular4 中,您必须将它放在根文件夹中。

Example:

例子:

Angular2:

角度2:

root / src / data / file.json

根/src/数据/file.json

Angular4:

角4:

root / data / file.json

根/数据/file.json