Angular 6 HttpClient JSON 对 myObject 的响应

Angular 6 HttpClient JSON response to myObject

我有一个 API,当使用 GET 查询时,returns 对象数组。 API 的响应格式为:

[
    {
        "Ident": "Ag",
        "Description": "Argent"
    },
    {
        "Ident": "As",
        "Description": "Arsenic"
    }
]

在我的应用程序中,我有一个具有以下结构的 Element 对象:

export class Element {
    public ident: string;
    public description: string;

    constructor(ident: string, description: string) {
        this.ident = ident;
        this.description = description;
    }
}

我的应用程序还有一项名为 mrcService 的服务,其中包含一个名为 getElements() 的函数,该函数将使用 HttpClient 和 returns 对象的 Observable 数组 Element:

getElements(): Observable<Element[]> {
  return this.http.get<Element[]>(this.apiUrl)
    .pipe(
      catchError(this.handleError('getElements', []))
    );
}

最后,我在 ngOnInit() {} 中有一个订阅此服务的组件,它获取 API 返回的数组的每个元素并推送他们组成一个数组:

elements: Array<Element> = [];
ngOnInit() {
    this.mrcService.getElements()
      .subscribe(res => {
        res.forEach(item => {
          this.elements.push(new Element(item.Ident, item.Description));
        });
        console.log(this.elements[0]); // returns the object at the index
      });
    console.log(this.elements[0]); // returns undefined
  }

我现在面临两个问题:

When pushing to my array, the observable properties must be referenced according to the nomenclature of the response by the API. I would like to use ident and * description* without capital letters like in my object definition instead of the capitalised letter from the API response

如果您无权访问 API 并且您仍然希望以这种方式访问​​它,您可以使用可观察地图运算符修改它以将对象属性键更改为您想要的方式。

I can't use this.elements[i] outside of .subscribe. When I do console.log(this.elements[i] it says undefined, but when I do console.log(this.elements) I can see the structure of the array.

请记住,可观察对象是异步的,因此当您在订阅之外进行 console.log 时,您的 http 请求尚未完成。