【问题标题】:Angular 5 Service to read local .json fileAngular 5服务读取本地.json文件
【发布时间】:2018-04-22 17:55:20
【问题描述】:

我正在使用 Angular 5,并且我使用 angular-cli 创建了一个服务

我想要做的是创建一个读取 Angular 5 本地 json 文件的服务。

这就是我所拥有的……我有点卡住了……

import { Injectable } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

@Injectable()
export class AppSettingsService {

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

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

  }

}

我怎样才能完成这项工作?

【问题讨论】:

标签: javascript json angular


【解决方案1】:

首先你必须注入HttpClient 而不是HttpClientModule, 第二件事你必须删除.map((res:any) =&gt; res.json()),你将不再需要它,因为新的HttpClient会默认为你提供响应的正文,最后确保你在AppModule中导入HttpClientModule

import { HttpClient } from '@angular/common/http'; 
import { Observable } from 'rxjs';

@Injectable()
export class AppSettingsService {

   constructor(private http: HttpClient) {
        this.getJSON().subscribe(data => {
            console.log(data);
        });
    }

    public getJSON(): Observable<any> {
        return this.http.get("./assets/mydata.json");
    }
}

将此添加到您的组件中:

@Component({
    selector: 'mycmp',
    templateUrl: 'my.component.html',
    styleUrls: ['my.component.css']
})
export class MyComponent implements OnInit {
    constructor(
        private appSettingsService : AppSettingsService 
    ) { }

   ngOnInit(){
       this.appSettingsService.getJSON().subscribe(data => {
            console.log(data);
        });
   }
}

【讨论】:

  • 我在这一行得到“Unresolved Type Observable”...“public getJSON(): Observable {”
  • 最后一个问题......我如何才能从我的组件中获取这些数据?
  • 假设我想读取 json id。我必须做什么?如果你不介意请给我这个例子。
  • 我在获取 json 文件时遇到了 404 错误......并且也像你一样遵循相同的流程......
  • 我收到 404 和日志GET http://localhost:4200/src/assets/data.json 404 (Not Found)
【解决方案2】:

对于 Angular 7,我按照以下步骤直接导入 json 数据:

在 tsconfig.app.json 中:

"compilerOptions"中添加"resolveJsonModule": true

在服务或组件中:

import * as exampleData from '../example.json';

然后

private example = exampleData;

【讨论】:

    【解决方案3】:

    您有一个替代解决方案,直接导入您的 json。

    要编译,请在您的 typings.d.ts 文件中声明此模块

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

    在您的代码中

    import { data_json } from '../../path_of_your.json';
    
    console.log(data_json)
    

    【讨论】:

    • 假设,我的 json 在 assets/abc.json 中,并且只使用一个模块 app.module.ts 然后如何在 typing.d.ts 中声明以及如何导入。请帮忙。
    • 只需在您的 typing.d.ts 文件中声明该模块。并将您的 JSON 导入您的班级
    • 哪个模块?假设我在应用程序中使用它。模块。 ts?
    • import { default as data_json } from '../../path_of_your.json';987654323@
    • 为什么我在控制台中得到“未定义”?
    【解决方案4】:

    我在寻找一种真正读取本地文件而不是从网络服务器读取文件的方法时发现了这个问题,我宁愿将其称为“远程文件”。

    只需拨打require

    const content = require('../../path_of_your.json');
    

    Angular-CLI 源代码启发了我:我发现它们包含组件模板,方法是将 templateUrl 属性替换为 template,并将值替换为 require 对实际 HTML 资源的调用。

    如果您使用 AOT 编译器,则必须通过调整 tsconfig.app.json 来添加节点类型定义:

    "compilerOptions": {
      "types": ["node"],
      ...
    },
    ...
    

    【讨论】:

    • 要使用require,我需要通过运行npm install @types/node --save-dev来安装@types/node,如here所讨论的那样
    • 所有这些解决方案都很棒,但这是唯一允许我保存值并动态解析文件内容而无需初始导入的解决方案之一
    【解决方案5】:
    import data  from './data.json';
    export class AppComponent  {
        json:any = data;
    }
    

    more details 见这篇文章。

    【讨论】:

    • 对于我的本地文件,这是最容易使用的。我必须将 "allowSyntheticDefaultImports": true 添加到我的 tsconfig.json 'compilerOptions' 中,但只是为了停止 TypeScript 的 linting 错误,而不是实际错误。
    • 这是解决方案:hackeruna.com/2020/04/27/… 用于此错误 TS1259
    【解决方案6】:

    假设您在项目的 src/app 文件夹中有一个 data.json 文件,其中包含以下值:

    [
        {
            "id": 1,
            "name": "Licensed Frozen Hat",
            "description": "Incidunt et magni est ut.",
            "price": "170.00",
            "imageUrl": "https://source.unsplash.com/1600x900/?product",
            "quantity": 56840
        },
        ...
    ]
    

    3种读取本地JSON文件的方法

    方法一:使用 TypeScript 2.9+ import 语句读取本地 JSON 文件

    import { Component, OnInit } from '@angular/core';
    import * as data from './data.json';
    
    @Component({
      selector: 'app-root',
      template: `<ul>
          <li *ngFor="let product of products">
    
          </li>
      </ul>`,
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
      title = 'Angular Example';
    
      products: any = (data as any).default;
    
      constructor(){}
      ngOnInit(){
        console.log(data);
      }
    }
    

    方法二:使用 Angular HttpClient 读取本地 JSON 文件

    import { Component, OnInit } from '@angular/core';
    import { HttpClient } from "@angular/common/http";
    
    
    @Component({
      selector: 'app-root',
      template: `<ul>
          <li *ngFor="let product of products">
    
          </li>
      </ul>`,
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
      title = 'Angular Example';
      products: any = [];
    
      constructor(private httpClient: HttpClient){}
      ngOnInit(){
        this.httpClient.get("assets/data.json").subscribe(data =>{
          console.log(data);
          this.products = data;
        })
      }
    }
    

    方法三:使用 ES6+ import 语句在离线 Angular 应用中读取本地 JSON 文件

    如果您的 Angular 应用程序离线,使用 HttpClient 读取 JSON 文件将失败。在这种情况下,我们还有一种方法可以使用支持导入 JSON 文件的 ES6+ import 语句来导入本地 JSON 文件。

    但首先我们需要添加一个打字文件如下:

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

    将此添加到 src/app 文件夹中的新文件 json-typings.d.ts 文件中。

    现在,您可以像 TypeScript 2.9+ 一样导入 JSON 文件。

    import * as data from "data.json";
    

    【讨论】:

      【解决方案7】:

      试试这个

      在你的服务中编写代码

      import {Observable, of} from 'rxjs';
      

      导入json文件

      import Product  from "./database/product.json";
      
      getProduct(): Observable<any> {
         return of(Product).pipe(delay(1000));
      }
      

      在组件中

      get_products(){
          this.sharedService.getProduct().subscribe(res=>{
              console.log(res);
          })        
      }
      

      【讨论】:

      • 对于那些无法在 tsconfig 中添加 "resolveJsonModule": true 的人的最佳答案
      【解决方案8】:

      让我们创建一个 JSON 文件,我们将其命名为 navbar.json,您可以随意命名!

      navbar.json

      [
        {
          "href": "#",
          "text": "Home",
          "icon": ""
        },
        {
          "href": "#",
          "text": "Bundles",
          "icon": "",
          "children": [
            {
              "href": "#national",
              "text": "National",
              "icon": "assets/images/national.svg"
            }
          ]
        }
      ]
      

      现在我们已经创建了一个包含一些菜单数据的 JSON 文件。我们将转到应用组件文件并粘贴以下代码。

      app.component.ts

      import { Component } from '@angular/core';
      import menudata from './navbar.json';
      
      @Component({
        selector: 'lm-navbar',
        templateUrl: './navbar.component.html'
      })
      export class NavbarComponent {
          mainmenu:any = menudata;
      
      }
      

      现在您的 Angular 7 应用已准备好从本地 JSON 文件中提供数据。

      转到 app.component.html 并在其中粘贴以下代码。

      app.component.html

      <ul class="navbar-nav ml-auto">
                        <li class="nav-item" *ngFor="let menu of mainmenu">
                        <a class="nav-link" href="{{menu.href}}">{{menu.icon}} {{menu.text}}</a>
                        <ul class="sub_menu" *ngIf="menu.children && menu.children.length > 0"> 
                                  <li *ngFor="let sub_menu of menu.children"><a class="nav-link" href="{{sub_menu.href}}"><img src="{{sub_menu.icon}}" class="nav-img" /> {{sub_menu.text}}</a></li> 
                              </ul>
                        </li>
                        </ul>
      

      【讨论】:

        【解决方案9】:

        使用 Typescript 3.6.3 和 Angular 6,这些解决方案都不适合我。

        所做的工作是遵循教程here,它说您需要将一个名为njson-typings.d.ts 的小文件添加到您的项目中,其中包含以下内容:

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

        完成后,我可以简单地导入我的硬编码 json 数据:

        import employeeData from '../../assets/employees.json';
        

        并在我的组件中使用它:

        export class FetchDataComponent implements OnInit {
          public employees: Employee[];
        
          constructor() {
            //  Load the data from a hardcoded .json file
            this.employees = employeeData;
            . . . .
          }
        

        【讨论】:

          猜你喜欢
          • 2018-06-25
          • 2019-11-24
          • 1970-01-01
          • 2018-06-09
          • 2018-11-03
          • 2018-06-27
          • 2021-08-21
          • 1970-01-01
          • 2012-11-28
          相关资源
          最近更新 更多