1. ホーム
  2. javascript

[解決済み] ローカルの.jsonファイルを読み込むAngular 5サービス

2022-09-15 17:27:50

質問

Angular5を使用しており、angular-cliを使用してサービスを作成しました。

やりたいことは、Angular5用のローカルの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));

  }

}

どうすれば完成するのでしょうか?

どのように解決するのですか?

まず 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に追加します。

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