小编典典

Angular 5 Service读取本地.json文件

javascript

我正在使用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));

  }

}

我该如何完成?


阅读 461

收藏
2020-05-01

共1个答案

小编典典

首先,你必须注入HttpClient和不HttpClientModule,你必须删除第二件事.map((res:any) => res.json()),你将不再需要它了,因为新HttpClient会给你默认响应的身体,最后确保你输入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");
    }
}

将此添加到您的组件:

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