简体   繁体   English

Angular HTTP-订阅提供了未解析的变量

[英]Angular HTTP - Subscribe gives unresolved variable

I have an APIService class with the next method: 我有一个带有下一个方法的APIService类:

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

I'm calling this method in component 我在组件中调用此方法

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

and I have an error on resp.data' - unresolved variable data . 并且我在resp.data' - unresolved variable dataresp.data' - unresolved variable data

All API responses have 'data' property. 所有API响应均具有“数据”属性。 The basic response structure from API is 'data' => [...] . API的基本响应结构是'data' => [...] How can I solve this problem? 我怎么解决这个问题? I hope I can create some basic type to annotate all API calls. 我希望我可以创建一些基本类型来注释所有API调用。

Try something like this, 试试这个

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

I've created a separate APIResponse to annotate response data from HTTP and then map data to Recipe[]. 我创建了一个单独的APIResponse来注释来自HTTP的响应数据,然后将数据映射到Recipe []。

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

Interface: 接口:

export interface APIResponse {
    data
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM