Don*_*ers 25 json typescript angular
使用Angular2和typescript,我从webApi返回JSON,我需要将它放入某种类型的数组中.我无法弄清楚如何将json转换为我需要的接口.
我的类型是这个界面:
export interface Country {
Id: number;
Name: string;
}
Run Code Online (Sandbox Code Playgroud)
我的mock返回这个数组:
export var COUNTRIES: Country[] = [
{ "Id": 11, "Name": "US" },
{ "Id": 12, "Name": "England" },
{ "Id": 13, "Name": "Japan" }
];
Run Code Online (Sandbox Code Playgroud)
这是我的代码:country.service.ts
@Injectable()
export class CountryService {
private _http = null;
constructor(http: Http) {
this._http = http;
}
getCountries() {
return Promise.resolve(COUNTRIES);
}
}
Run Code Online (Sandbox Code Playgroud)
然后我用它来称呼它:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我有一个名为countries的类变量,它是Country接口的数组.这按预期工作.(我知道我不需要那个setData方法 - 它用于调试)
接下来,我将服务更改为wepApi调用,返回此json.
"[{"name":"England","id":1},{"name":"France","id":2}]"
Run Code Online (Sandbox Code Playgroud)
我将服务中的getCountries方法更改为:
getCountries() {
return new Promise(resolve=>
this._http.get('http://localhost:63651/Api/membercountry')
.subscribe(data => resolve(data.json()))
);
}
Run Code Online (Sandbox Code Playgroud)
使用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()))
);
}
Run Code Online (Sandbox Code Playgroud)
我找不到关于此的文档.当我尝试它时,我从来没有得到数据,但没有错误.没有编译错误,也没有运行时错误.
tos*_*skv 15
您可以对JSON.parse创建的对象所期望的接口执行类型断言.
this.http.get('http://localhost:4200/').subscribe((value: Response) => {
let hero = <ServerInfo>value.json();
});
Run Code Online (Sandbox Code Playgroud)
但是,如果服务器由于两个原因向您发送了坏对象,则不会导致任何错误.
在编译时,转换器不知道服务器将发送什么.
在运行时,所有类型信息都被删除,因为所有类型信息都被编译为javascript.
Viktor Savkin有一个库可以针对这种情况进行类型的运行时检查,但不适用于接口,因为Typescript不会在接口上导出运行时信息。有一个关于这个的讨论在这里。
有两种可能的解决方案:
总的来说,我看到Typescript的类型比编译器暗示的要多于严格的类型系统-毕竟它必须编译成无类型的语言。
归档时间: |
|
查看次数: |
37817 次 |
最近记录: |