如何使用angular2向客户端读取JSON
我有一个数据,我必须将该数据读入html并显示值。 我尝试过通过API调用JSON的方法,但没有成功。请看一下我的代码演示 有没有什么方法可以不用API调用就使用这些数据,我使用了JSON文件,因为我不希望这个文件太长 HTML: 请尝试以下操作:如何使用angular2向客户端读取JSON,angular,Angular,我有一个数据,我必须将该数据读入html并显示值。 我尝试过通过API调用JSON的方法,但没有成功。请看一下我的代码演示 有没有什么方法可以不用API调用就使用这些数据,我使用了JSON文件,因为我不希望这个文件太长 HTML: 请尝试以下操作: export class AppComponent { constructor(private http: HttpClient) { this.getCountryList().subscribe(data => {
export class AppComponent {
constructor(private http: HttpClient) {
this.getCountryList().subscribe(data => {
this.countryList=data;
});
}
public getCountryList():Observable<any> {
return this.http.get("./assets/countrylist.json")
}
}
而不是:
import { Http } from '@angular/http';
以及:
而不是:
import { HttpModule } from '@angular/http';
如果在应用程序中包含数据,则无需进行ajax调用。只需从json文件导入它并公开
import allCountries from './countrylist.json'
然后你的名单就可以作为所有国家访问了
您还可以从.json文件导入所有数据:
import * as data from './file.json';
然后将其用作数据变量。不要使用不推荐使用的Http服务。使用记录在案的HttpClient。并将JSON放在服务器将提供服务的位置,原样。对于Angular CLI,这意味着资产不足。但是,如果您同意将其作为应用程序本身的一部分,那么您可以直接输入TypeScript源代码。是的,该类型脚本文件将很长。那又怎样?你得到我的答案了吗?
import { HttpModule } from '@angular/http';
import allCountries from './countrylist.json'
constructor(private http: Http
) {
this.countryList=allCountries;
}
import * as data from './file.json';