Javascript Angular 5 Service 读取本地 .json 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47206924/
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 03:47:06  来源:igfitidea点击:

Angular 5 Service to read local .json file

javascriptjsonangular

提问by Bougarfaoui El houcine

I am using Angular 5 and I've created a service using the angular-cli

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

What I want to do is to create a service that reads a local json file for Angular 5.

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

This is what I have ... I'm a bit stuck...

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

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));

  }

}

How can I get this finished?

我怎样才能完成这个?

回答by Bougarfaoui El houcine

First You have to inject HttpClientand Not HttpClientModule, second thing you have to remove .map((res:any) => res.json())you won't need it any more because the new HttpClientwill give you the body of the response by default , finally make sure that you import HttpClientModulein your AppModule:

首先你必须注入HttpClient而不是HttpClientModule,第二件事你必须删除.map((res:any) => res.json())你不再需要它,因为HttpClient默认情况下new会给你响应的正文,最后确保你导入HttpClientModule你的AppModule

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");
    }
}

to add this to your Component:

将此添加到您的组件中:

@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);
        });
   }
}

回答by Nicolas Law-Dune

You have an alternative solution, importing directly your json.

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

To compile, declare this module in your typings.d.ts file

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

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

In your code

在你的代码中

import { data_json } from '../../path_of_your.json';

console.log(data_json)

回答by jaycer

For Angular 7, I followed these steps to directly import json data:

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

In tsconfig.app.json:

在 tsconfig.app.json 中:

add "resolveJsonModule": truein "compilerOptions"

添加"resolveJsonModule": true"compilerOptions"

In a service or component:

在服务或组件中:

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

And then

进而

private example = exampleData;

回答by fishbone

I found this question when looking for a way to really read a local file instead of reading a file from the web server, which I'd rather call a "remote file".

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

Just call require:

只需致电require

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

The Angular-CLI source code inspired me: I found out that they include component templates by replacing the templateUrlproperty by templateand the value by a requirecall to the actual HTML resource.

Angular-CLI 源代码启发了我:我发现它们通过调用实际 HTML 资源来替换templateUrl属性template和值来包含组件模板require

If you use the AOT compiler you have to add the node type definitons by adjusting tsconfig.app.json:

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

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

回答by Ole

import data  from './data.json';
export class AppComponent  {
    json:any = data;
}

See this article for more details.

有关更多详细信息,请参阅此文章。

回答by Ole

Try This

尝试这个

Write code in your service

在您的服务中编写代码

import {Observable, of} from 'rxjs';

import json file

导入json文件

import Product  from "./database/product.json";

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

In component

在组件中

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

回答by Surya R Praveen

Let's create a JSON file, we name it navbar.json you can name it whatever you want!

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

navbar.json

导航栏.json

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

Now we've created a JSON file with some menu data. We'll go to app component file and paste the below code.

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

app.component.ts

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;

}

Now your Angular 7 app is ready to serve the data from the local JSON file.

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

Go to app.component.html and paste the following code in it.

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

app.component.html

应用程序组件.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>

回答by Mike Gledhill

Using Typescript 3.6.3, and Angular 6, none of these solutions worked for me.

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

What didwork was to follow the tutorial herewhich says you need to add a small file called njson-typings.d.tsto your project, containing this:

什么的工作是按照教程在这里它说你需要添加一个名为小文件njson-typings.d.ts到您的项目,包含此:

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

Once this was done, I could simply import my hardcoded json data:

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

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

and use it in my component:

并在我的组件中使用它:

export class FetchDataComponent implements OnInit {
  public employees: Employee[];

  constructor() {
    //  Load the data from a hardcoded .json file
    this.employees = employeeData;
    . . . .
  }