代码之家  ›  专栏  ›  技术社区  ›  Denys Siebov

角度http-subscribe提供未解析的变量

  •  0
  • Denys Siebov  · 技术社区  · 6 年前

    我有一个具有下一个方法的apiservice类:

      public getRecipeIndex() : Observable<Recipe[]>
      {
        return this.http.get<Recipe[]>(this.serverURL+'recipes');
      }
    

    我在组件中调用这个方法

      ngOnInit() {
        this.api.getRecipeIndex()
            .subscribe(
                resp => this.recipes = resp.data
            );
      }
    

    我有个错误 resp.data' - unresolved variable data .

    所有API响应都具有“data”属性。 API的基本响应结构是 'data' => [...] . 我怎样才能解决这个问题?我希望可以创建一些基本类型来注释所有API调用。

    2 回复  |  直到 6 年前
        1
  •  0
  •   Anil Kumar Reddy A    6 年前

    尝试这样的方法,

     ngOnInit() {
            this.api.getRecipeIndex()
                .subscribe(resp=>{    
                   this.recipes = resp;
                   });
                }
    
        2
  •  -1
  •   Denys Siebov    6 年前

    我已经创建了一个单独的APIResponse来注释来自HTTP的响应数据,然后将数据映射到配方[]。

      public getRecipeIndex() : Observable<Recipe[]>
      {
        return this.http.get<APIResponse>(this.serverURL+'recipes')
            .pipe(
                map(response => response.data)
            );
      }
    

    接口:

    export interface APIResponse {
        data
    }