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/Observable';
@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文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!