我想从json文件中获取数据并分配给整个应用程序(大量页面)的数组(国家/地区),但是当我致电GetCountries时方法,国家不确定,我的方法有什么问题?
import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
@Injectable()
export class CountryService {
private countries: any;
private isLoaded: boolean;
private url: string = 'http://localhost:8100/assets/data/countriesV2.json';
constructor(private http: Http) {
if (!this.isLoaded) {
this.http.get(this.url)
.map(res => res.json())
.subscribe(result => {
this.countries = result;
});
this.isLoaded = true;
}
}
public getCountries() {
console.log(this.countries);
return this.countries();
}
}
也许将return this.countries();
更改为return this.countries;
可能会有所帮助
另外,检查您的结果不是空的:
.subscribe(result => {
this.countries = result;
console.log(result)
});
您应始终映射服务中的数据,并在组件中订阅。this.countries
之所以不确定,是因为它是未定义的,即使您试图在构造函数中执行请求,也无法正常工作。更改您的服务:
@Injectable()
export class CountryService {
private url: string = 'http://localhost:8100/assets/data/countriesV2.json';
constructor(private http: Http) { }
public getCountries() {
this.http.get(this.url)
.map(res => res.json())
}
}
然后在您的组件中您致电getCountries
并订阅请求。
countries: any[] = [];
constructor(private countryService: CountryService) { }
ngOnInit() {
this.countryService.getCountries()
.subscribe(data => {
this.countries = data;
// here countries is not undefined, so call your "randomCountry" method here!
this.getRandomCountry();
});
}
由于这是一个异步操作,我建议您在该视图中使用安全的导航操作员,如果国家/地区无效,则不会试图显示国家的财产。更多信息此处。因此,用法将是:
<div *ngFor="let country of countries">
{{country?.yourProperty}} // replace "yourProperty" with your actual property
</div>
此处从官方文档
中提供了一些有关HTTP的更详细说明希望这会有所帮助!:)