【发布时间】:2016-04-03 15:35:01
【问题描述】:
使用 Angular2 和 typescript,我从 webApi 返回 JSON,我需要将它放入特定类型的数组中。我不知道如何将 json 转换为我需要的接口。
我的类型是这个界面:
export interface Country {
Id: number;
Name: string;
}
我的模拟返回这个数组:
export var COUNTRIES: Country[] = [
{ "Id": 11, "Name": "US" },
{ "Id": 12, "Name": "England" },
{ "Id": 13, "Name": "Japan" }
];
这是我的代码: country.service.ts
@Injectable()
export class CountryService {
private _http = null;
constructor(http: Http) {
this._http = http;
}
getCountries() {
return Promise.resolve(COUNTRIES);
}
}
然后我用这个来称呼它:
export class CountryPickerComponent {
public countries: Country[];
constructor(private _countryService: CountryService) { }
getCountries() {
this._countryService.getCountries().then(data => this.setData(data));
}
setData(data) {
//this.countries = data;
this.countries = JSON.parse(data);
var q = 1;
}
ngOnInit() {
this.getCountries();
}
}
如您所见,我有一个名为 countries 的类变量,它是 Country 接口的数组。这按预期工作。 (我知道我不需要那个 setData 方法——它是用来调试的)
接下来,我将服务更改为返回此 json 的 wepApi 调用。
"[{"name":"England","id":1},{"name":"France","id":2}]"
我将服务中的 getCountries 方法更改为:
getCountries() {
return new Promise(resolve=>
this._http.get('http://localhost:63651/Api/membercountry')
.subscribe(data => resolve(data.json()))
);
}
使用 JSON.parse,我将它转换为一个数组,然后我可以在 angular2 中使用它。有用。它使用数据创建数组。但它不是实现 Country 接口的数组。
请注意,JSON 中的字段名称都是小写的,但接口属性以大写开头,我对接口进行了编码。结果,当我得到真正的 json 时,它不起作用。有没有办法将它“投射”到界面,这应该会引发错误并让我知道有什么问题?
很多例子在get中使用map如下所示:
getCountries() {
var retVal;
return new Promise(resolve=>
this._http.get('http://localhost:63651/Api/membercountry')
.map(ref => ref.json())
.subscribe(data => resolve(data.json()))
);
}
我找不到这方面的文档。当我尝试它时,我永远不会得到数据,但没有错误。没有编译错误,也没有运行时错误。
【问题讨论】:
-
如果你使用
angular 2 beta,map在Observable中不可用,从http.get()返回,而是subscribe直接在Observable上使用。
标签: json typescript angular