Angular 5 Service读取本地.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<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({

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

});

}

}

以上是 Angular 5 Service读取本地.json文件 的全部内容, 来源链接: utcz.com/qa/407872.html

回到顶部