Javascript Angular 5服务读取本地.json文件
我正在使用Angular 5,我已经使用Angular cli创建了一个服务 我想做的是创建一个服务,为Angular 5读取本地json文件 这就是我所拥有的。。。我有点卡住了Javascript Angular 5服务读取本地.json文件,javascript,json,angular,Javascript,Json,Angular,我正在使用Angular 5,我已经使用Angular cli创建了一个服务 我想做的是创建一个服务,为Angular 5读取本地json文件 这就是我所拥有的。。。我有点卡住了 import { Injectable } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; @Injectable() export class AppSettingsService { constru
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));
}
}
从'@angular/core'导入{Injectable};
从'@angular/common/http'导入{HttpClientModule};
@可注射()
导出类应用程序设置服务{
构造函数(专用http:HttpClientModule){
var-obj;
this.getJSON().subscribe(data=>obj=data,error=>console.log(error));
}
public getJSON():可观察{
返回此.http.get(“./assets/mydata.json”)
.map((res:any)=>res.json())
.catch((错误:any)=>console.log(错误));
}
}
如何完成此操作?首先必须插入
HttpClient
,而不是HttpClientModule
,
第二件事是您必须删除.map((res:any)=>res.json())
您将不再需要它,因为新的HttpClient
将默认为您提供响应的主体,最后确保您在AppModule
中导入HttpClientModule
:
您有另一种解决方案,直接导入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)
我在寻找一种真正读取本地文件而不是从web服务器读取文件(我更愿意称之为“远程文件”)的方法时发现了这个问题 只需调用
require
:
const content = require('../../path_of_your.json');
Angular CLI源代码启发了我:我发现它们包括组件模板,方法是将templateUrl
属性替换为template
,将值替换为对实际HTML资源的require
调用
如果使用AOT编译器,则必须通过调整tsconfig.app.json
,添加节点类型定义:
"compilerOptions": {
"types": ["node"],
...
},
...
参见本文。对于Angular 7,我按照以下步骤直接导入json数据:
import employeeData from '../../assets/employees.json';
在tsconfig.app.json中:
在“编译器选项”
在服务或组件中:
import * as exampleData from '../example.json';
export class FetchDataComponent implements OnInit {
public employees: Employee[];
constructor() {
// Load the data from a hardcoded .json file
this.employees = employeeData;
. . . .
}
然后
private example = exampleData;
试试这个
在服务中编写代码
import {Observable, of} from 'rxjs';
导入json文件
import Product from "./database/product.json";
getProduct(): Observable<any> {
return of(Product).pipe(delay(1000));
}
让我们创建一个JSON文件,我们将其命名为navbar.JSON您可以随意命名它 navbar.json
[
{
"href": "#",
"text": "Home",
"icon": ""
},
{
"href": "#",
"text": "Bundles",
"icon": "",
"children": [
{
"href": "#national",
"text": "National",
"icon": "assets/images/national.svg"
}
]
}
]
现在我们已经创建了一个包含一些菜单数据的JSON文件。我们将转到应用程序组件文件并粘贴以下代码
应用程序组件.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>
-
使用Typescript 3.6.3和Angular 6,这些解决方案都不适合我
我们所做的工作是遵循教程的要求,即需要向项目中添加一个名为njson typings.d.ts
的小文件,其中包含以下内容:
declare module "*.json" {
const value: any;
export default value;
}
完成后,我可以简单地导入硬编码的json数据:
import employeeData from '../../assets/employees.json';
并在我的组件中使用它:
import * as exampleData from '../example.json';
export class FetchDataComponent implements OnInit {
public employees: Employee[];
constructor() {
// Load the data from a hardcoded .json file
this.employees = employeeData;
. . . .
}
假设项目的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文件的方法
方法1:使用TypeScript 2.9+import语句读取本地JSON文件
将其添加到src/app文件夹中的新文件json typings.d.ts
中
现在,您可以像TypeScript 2.9+一样导入JSON文件
import * as data from "data.json";
例如,
HttpClientModule
不应该被注入构造函数中。。。在这一行“public getJSON():Observable{”最后一个问题…我如何从我的组件中读取这些数据?假设我想读取json id。我必须做什么?如果你不介意的话,请给我提供一个例子。我在获取json文件时遇到了404错误…并且也遵循与你相同的流程。假设我在assets/abc.json中有我的json,并且只使用一个模块app.module.ts,那么如何在typing.d.ts中声明以及如何导入。请提供帮助。只需在typing.d.ts文件中声明模块。然后将JSON导入到类中哪个模块?假设我在app.module.ts中使用它?当我从“../../../path\u of_your.JSON”导入{default as data_JSON}”时,我得到“未定义”的原因是什么在控制台中?要使用require
我需要通过运行npm install@types/node--save dev
来安装@types/node
,如前所述,所有这些解决方案都很棒,但这是唯一允许我保存值并动态解析文件内容的解决方案之一,而无需对mom的初始importBest回答对于那些无法将“resolveJsonModule”:true添加到他们的tsconfig中的人来说,这是最容易使用的。我必须将“allowSyntheticDefaultImports”:true
添加到我的tsconfig.json“compilerOptions”中,但只是为了停止TypeScript的linting错误,而不是实际错误。这是解决方案:对于此错误TS1259
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);
}
}
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;
})
}
}
declare module "*.json" {
const value: any;
export default value;
}
import * as data from "data.json";