[英]Angular 5 Service to read local .json file
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?我怎样才能完成这个?
First You have to inject HttpClient
and Not HttpClientModule
, second thing you have to remove .map((res:any) => res.json())
you won't need it any more because the new HttpClient
will give you the body of the response by default , finally make sure that you import HttpClientModule
in your AppModule
:首先你必须注入
HttpClient
而不是HttpClientModule
,第二件事你必须删除.map((res:any) => 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");
}
}
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);
});
}
}
For Angular 7, I followed these steps to directly import json data:对于 Angular 7,我按照以下步骤直接导入 json 数据:
In tsconfig.app.json:在 tsconfig.app.json 中:
add "resolveJsonModule": true
in "compilerOptions"
在
"compilerOptions"
添加"resolveJsonModule": true
In a service or component:在服务或组件中:
import * as exampleData from '../example.json';
And then接着
private example = exampleData;
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)
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 templateUrl
property by template
and the value by a require
call to the actual HTML resource. Angular-CLI 源代码启发了我:我发现它们包含组件模板,方法是将
templateUrl
属性替换为template
,并将值替换为对实际 HTML 资源的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"],
...
},
...
import data from './data.json';
export class AppComponent {
json:any = data;
}
See this article for more details .有关更多详细信息,请参阅此文章。
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);
})
}
Assumes, you have a data.json file in the src/app folder of your project with the following values:假设您在项目的 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
},
...
]
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;
})
}
}
But first we need to add a typing file as follows:但首先我们需要添加一个打字文件,如下所示:
declare module "*.json" { const value: any; export default value; }
Add this inside a new file json-typings.d.ts
file in the src/app folder.将此添加到 src/app 文件夹中的新文件
json-typings.d.ts
文件中。
Now, you can import JSON files just like TypeScript 2.9+.现在,您可以像 TypeScript 2.9+ 一样导入 JSON 文件。
import * as data from "data.json";
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.现在我们已经创建了一个包含一些菜单数据的 JSON 文件。 We'll go to app component file and paste the below code.
我们将转到应用组件文件并粘贴以下代码。
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>
Using Typescript 3.6.3, and Angular 6, none of these solutions worked for me.使用 Typescript 3.6.3 和 Angular 6,这些解决方案都不适合我。
What did work was to follow the tutorial here which says you need to add a small file called njson-typings.d.ts
to 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;
. . . .
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.