我有一个像下面这样的json。
private _ELEMENT_DATA: Account[] = [
{"id":{"name":"abc", "value":"123"}},
{"id":{"name":"abc", "value":"123"}},
{"id":{"name":"abc", "value":"123"}}
]请帮我分析一下角6。
export class Account{
name: string;
value: string;
}我的服务班是这样的
getAllAccouts(): Observable<any[]> {
// return this.httpClient.get<Account[]>(this.ELEMENT_DATA);
return of<Account[]>(this._ELEMENT_DATA);
} 发布于 2019-03-06 18:09:52
如果您正在寻找与类Account匹配的结果,那么首先,您的"json“(实际上是JS数组)不能具有Account[]类型,因此必须是一个保存Account对象的模型。这里我借用杰米的模型:
export interface AccountContainer {
id: Account;
}
export interface Account {
name: string;
value: string;
}
private _ELEMENT_DATA: AccountContainer[] = [
{ "id": { "name": "abc", "value": "123" } },
{ "id": { "name": "abc", "value": "123" } },
{ "id": { "name": "abc", "value": "123" } }
]另外,由于您没有构造函数或类的方法,所以接口就足够了。因此,要获得您想要的结果,请执行以下操作:
import { map } from 'rxjs/operators';
// ....
getAllAccouts(): Observable<Account[]> {
return of<AccountContainer[]>(this._ELEMENT_DATA).pipe(
map(x => x.map(y => <Account>{ name: y.id.name, value: y.id.value }))
)
}这样,就可以得到一个与Account接口相匹配的对象数组。
发布于 2019-03-06 16:09:47
这个JSON将不能被解析到类中。
你需要这样的一门课:
export class AccountContainer {
id: Account;
}并将服务代码更改为:
getAllAccouts(): Observable<AccountContainer[]> {
return of<AccountContainer[]>(this._ELEMENT_DATA);
} https://stackoverflow.com/questions/55027460
复制相似问题