【问题标题】:Type 'Promise<any>' is missing the following properties类型“Promise<any>”缺少以下属性
【发布时间】:2019-12-24 22:54:43
【问题描述】:

我正在使用来自 @angular/common/http 的 HttpClient 和 HttpResponse(认为在包中不可用)从 Fiberbase 以 agular 获取响应,但是在映射响应时存在一些类型转换问题,因为我认为响应生成 Observable 为返回类型。任何人都可以建议我哪里出错了。

我在分配 const 配方时遇到错误(“类型 'Promise' 缺少类型 'Recipe[]' 中的以下属性:长度、pop、push、concat 和另外 26 个”)

import { HttpClient,HttpResponse } from '@angular/common/http';
getRecipes(){
        this.http.get('https://ng-recipe-book-cb551.firebaseio.com/recipes.json')
        .map(
            (response: Response) => {
                const recipes: Recipe[] = response.json();
                for(let recipe of recipes){
                    if(!recipe['ingredients']){
                        recipe['ingredients'] = [];
                    }
                }
                return recipes;
            }
        )
            .subscribe(
                (recipes: Recipe[]) => {
                    this.recipeService.setRecipes(recipes);
                }
            );
    }

我应该从 response.json 中获取食谱数组

【问题讨论】:

  • Angular 是什么版本的? (在 ng5+ 中你需要使用管道并在管道中添加地图)
  • @reza 我正在使用 Angular cli v 8.1.2
  • 如果你使用的是ng8,你根本不需要做response.json

标签: angular


【解决方案1】:

response.json() 返回一个 Promise。尝试使用 JSON.parse(response) 代替它会将您的数组解析为可用的形式。

【讨论】:

    【解决方案2】:

    你需要这样做

    export interface Recipe {
    
      description: string
      imagePath: string,
      ingredients: Array<{
        amount: number,
        name: string}>,
      name: string
    }
    
       this.http.get<Array<Recipe>>('https://ng-recipe-book-cb551.firebaseio.com/recipes.json')
        .pipe(
          map(data => {
            return data.map((i: Recipe) => {
    
              if (i.ingredients == null) {
                i.ingredients = [];
              }
    
              return i;
            });
          })
    

    查看工作示例here

    【讨论】:

      【解决方案3】:

      我尝试了您的代码,但您使用了错误的接口类型 Response,这会导致您遇到错误。

      我建议您从 docs 阅读 http-client 以了解 HttpClient 的工作原理。 HttpClient 会解析您对对象的响应,因此您也不需要使用response.json()

      您还应该使用可管道操作符。检查map 的导入并将您的代码更改为:

      import { map } from 'rxjs/operators';
      
      // ...
      
      return this.http.get<Recipe[]>('...').pipe(
        map((response: Recipe[]) => {
          for (let recipe of response) {
            if (!recipe['ingredients']) {
              recipe['ingredients'] = [];
            }
           }
           return response;
          }
        )
      )
      

      我还想知道 firebase 的使用,如果您实际上在项目中使用 firebase,我建议您研究 angularfire 以“正确”使用它,我们通常不使用 http-requests 来获取数据来自火力基地。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-02
        • 1970-01-01
        • 2020-09-12
        • 2021-04-02
        • 2019-09-11
        • 1970-01-01
        • 2019-04-28
        相关资源
        最近更新 更多