读取本地.json文件的Angular 5服务
我使用的是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));
}
}
我怎样才能完成这个任务?
78
3
首先你必须注入
HttpClient
而不是HttpClientModule
。 其次,你必须删除.map((res:any) => res.json())
,你将不再需要它,因为新的HttpClient
会默认给你响应的主体,最后确保你在AppModule
中导入HttpClientModule
。 :来将其添加到你的组件中。
你有一个替代解决方案,直接导入你的json。
为了编译,在你的typings.d.ts文件中声明这个模块
在你的代码中
我在寻找一种真正读取本地文件的方法时发现了这个问题,而不是从网络服务器上读取文件,我宁愿把它称为"远程文件" 。
只要调用
require
就可以了。Angular-CLI的源代码启发了我。我发现他们通过用
template
替换templateUrl
属性,用require
调用实际的HTML资源的值来包含组件模板。如果你使用AOT编译器,你必须通过调整
tsconfig.app.json
来添加节点类型定义。