Angular 5 Service 读取本地 .json 文件 [英] Angular 5 Service to read local .json file
问题描述
我正在使用 Angular 5 并且我已经使用 angular-cli 创建了一个服务
I am using Angular 5 and I've created a service using the angular-cli
我想做的是为Angular 5创建一个读取本地json文件的服务.
What I want to do is to create a service that reads a local json file for Angular 5.
这就是我所拥有的……我有点卡住了……
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));
}
}
我怎样才能完成这个?
推荐答案
首先你必须注入 HttpClient
而不是 HttpClientModule
,第二件事你必须删除 .map((res:any) => res.json())
你不再需要它,因为新的 HttpClient
会默认情况下为您提供响应正文,最后确保您在 AppModule
中导入 HttpClientModule
:
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
:
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);
});
}
}
这篇关于Angular 5 Service 读取本地 .json 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!