Angular 5服务读取本地.json文件

33 浏览
0 Comments

Angular 5服务读取本地.json文件

我正在使用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 {
    return this.http.get("./assets/mydata.json")
      .map((res:any) => res.json())
      .catch((error:any) => console.log(error));
  }
}

我该如何完成它?

admin 更改状态以发布 2023年5月25日
0
0 Comments

对于Angular 7,我采取了以下步骤来直接导入JSON数据:

在tsconfig.app.json文件中:

"compilerOptions"中添加"resolveJsonModule": true

在一个服务或组件中:

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

然后

private example = exampleData;

0
0 Comments

首先,您必须注入 HttpClient,而不是 HttpClientModule。其次,您必须删除 .map((res:any) => res.json()),因为新的 HttpClient 默认会给您响应的 body。最后,请确保您在 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 {
        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);
        });
   }
}

0