首页 > 解决方案 > 如何将结构化数据转化为可观察数据?

问题描述

我有一个返回一些结构化数据的 web api。

{
    i: {
        f: [...],
        a: val,
        b: val
    },
    a: [...],
    b: [...],
    c: [...]
}

我将此返回到 Angular 6 应用程序 - 我假设使用 Observables 和 rxjs。我在可观察对象中看到的所有示例都假定一个数组被强制转换为可观察对象。但是,此数据是结构化的,并且在该结构中包含一些子数组。

我是 Angular 的新手,所以如果可能的话,我正在寻找一些方向。

标签: angulartypescriptrxjs

解决方案


服务:

import {
    HttpClient,
    HttpErrorResponse,
    HttpEvent,
    HttpHandler,
    HttpInterceptor,
    HttpRequest,
    HttpHeaders
} from '@angular/common/http';

constructor(private httpClient: HttpClient,
        ) {
    }

    /**
     * This method is use for send GET http Request to API.
     * @param url - Additional request URL.
     * @param options  - Header(s) which will pass with particular request.
     */
    get(url: string, options?: any): Observable<any> {

        return this.httpClient.get(url, this.requestOptions(options))
    }





   /**
    * Request options.
    * @param headerOptions
    * @returns {RequestOptionsArgs}
    */
    private requestOptions(headerOptions?: any): any {
        options = {
                    headers: new HttpHeaders({
                        "Authorization": "Bearer " + token,
                        "Content-Type": "application/json"
                    })
                }
             }

组件.ts:

 myData: Array<any>;

    /**
     * This method is used to get  data
     */
    getFormData(filter) {

        this.requestURL = `your_url`;

         this.http.get(this.requestURL, options).subscribe(response => {

              this.myData = response as ArrayCast[]
              console.log(response)
            })
           ;
    }

export class ArrayCast{
  a: any;
  b: any;
  c: any;
}

推荐阅读