【问题标题】:typescript problem with adding array of objects to new array将对象数组添加到新数组的打字稿问题
【发布时间】:2022-01-24 10:41:33
【问题描述】:

我正在尝试在前端显示我的数据(食谱)。当我从服务器获取 console.log(data) 时,我有一个对象,其属性为“msg”,其中包含对象数组。 我可以使用data['msg' as keyof typeof data]) 访问该数组 所以当我 console.log 我得到一个对象数组logging msg property of data 现在我的问题是当我尝试将该数组分配给this.recipe 数组时。 当我尝试this.recipe = data['msg' as keyof typeof data] 时出现错误:

类型“Function”缺少类型“Recipe[]”中的以下属性:pop、push、concat、join 等 27 个。

但是当我尝试使用 push() 时,我得到了

“功能”类型缺少“配方”类型的以下属性:描述、成分

我对 Angular 比较陌生,我迷路了。 如果您需要我的其他代码块,现在让我来,我不想复制粘贴很多,因为我不确定问题出在哪里,什么会有帮助。我把文件放在这里问题。

我遇到问题的代码:

export class ListComponent implements OnInit {
  public recipes: Recipe[];
  constructor(private _recipeService: RecipeService) { }

  ngOnInit(): void {
    this.readRecipes();
  }
  readRecipes() {
    this._recipeService.readRecipes().subscribe({
      next: (data) => {
        this.recipes = data['msg' as keyof typeof data];
      }
      ,
      error: (error) => console.log(error),
      complete: () => console.info('complete')

    }

    )
  }

}

我的 recipe.service.ts 文件:

export class RecipeService {
  private baseUri: string = "http://localhost:8080";
  private headers = new HttpHeaders().set('Content-Type', 'application/json')
  constructor(private http: HttpClient) { }


  createRecipe(recipe: Recipe) {
    return this.http.post(this.baseUri + '/create', recipe, { headers: this.headers });
  }

  readRecipes() {
    return this.http.get(this.baseUri + '/read', { headers: this.headers });
  }

  updateRecipe(recipe: Recipe) {
    return this.http.put(this.baseUri + '/update', recipe, { headers: this.headers });
  }

  deleteRecipe(id: string) {
    return this.http.delete(this.baseUri + '/delete/' + id, { headers: this.headers });
  }
}

读取路径的后端部分代码:

router.get('/read', (req, res, next) => {
Recipe.find({}, (err, recipes) => {
    if (err)
        res.status(500).json({
            errmsg: err
        });
    res.status(200).json({
        msg: recipes
    });

});
});

【问题讨论】:

  • 嗨,欢迎来到 Stack Overflow。请通过将源代码和 JSON 数据附加为 sn-ps 而不是图像来提供Minimal, Reproducible Example。谢谢。
  • 请尝试将代码上传到stackblitz
  • 我编辑了我的第一篇文章,希望它现在更具可读性。谢谢

标签: angular typescript


【解决方案1】:

更简单的方法是在 Angular 中使用 async 管道:

@Component({
  template: `
    <ul *ngIf="(employees$ | async).length">
      <li *ngFor="let employee of employees$ | async">{{employee.name}}</li>
    </ul>  
  `
})
export class EmployeesComponent implements OnInit { 
  employees$: Observable<Employee[]>;
 
  constructor(private service: MyService) {}
 
  ngOnInit() {
    this.employees$ = this.service.getEmployees$();
  }
}

这是您的 Stackblitz 的一个分支,其中显示了食谱列表:https://stackblitz.com/edit/angular-ivy-r97jph?file=src/app/components/list/list.component.ts

【讨论】:

  • 我试过了,但我又遇到了类似的问题。现在我得到“类型'对象'缺少来自类型'Recipe []'的以下属性:长度、弹出、推送、连接和还有 28 个。”
  • @PezerAFC 请提供 Stackblitz 链接,我很乐意为您提供帮助。
  • 谢谢..我以前从未使用过Stackblitz,所以我希望我做得很好...这是前端部分的链接:stackblitz.com/edit/angular-ivy-y9kzl9 后端:stackblitz.com/edit/node-padpgx
【解决方案2】:

只是写在这里,我找到了解决方案。

在后端,我以res.JSON({msg:recipes}) 发送响应,但我无法访问msg 对象,但是当我将代码更改为res.JSON(recipes) 并且只有括号() 时,我能够获取数组。然后使用新的data 变量,我使用this.recipes=data 访问响应数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 2020-05-11
    • 2022-01-21
    • 2016-01-14
    • 2021-02-24
    • 2020-08-06
    相关资源
    最近更新 更多