首页 > 解决方案 > 类型对象中缺少尝试访问角度 6 属性 ID 中的对象数据

问题描述

我创建了一个如下所示的界面:-

export interface Recipe {
    id: number;
    likes: number[];
}

我的组件看起来像这样:-

import { Component, OnInit } from '@angular/core';
import {RecipeService } from '../../recipe.service';
import {Observable } from 'rxjs';
import {Recipe} from '../../recipe.interface';


@Component({
  selector: 'app-recent-blog-recipes',
  templateUrl: './recent-blog-recipes.component.html',
  styleUrls: ['./recent-blog-recipes.component.scss'],

})
export class RecentBlogRecipesComponent implements OnInit {

    recipes$: Object;
  likes$ : Recipe[];

  constructor(private data: RecipeService ) { }

  ngOnInit() {
    this.data.getUserId().subscribe(
      data => {
        this.likes$.push(data);
        console.log(this.likes$);
        },
      error => console.log(error)
    )
  }
}

当我编译它时,我得到这个错误:

ERROR in src/app/welcome/recent-blog-recipes/recent-blog-recipes.component.ts(52,26): error TS2345: Argument of type 'Object' is not assignable to parameter of type 'Recipe'.
  The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
    Property 'id' is missing in type 'Object'.

这怎么可能,我在界面中有id?在我尝试将它推入“likes$[]”数组之前,我从对象记录的数据也看起来像这样:-

{id:1,喜欢:[1,2,12]}

知道有什么问题吗?

标签: typescriptangular6

解决方案


因为likes$Recipe[],您需要确保返回类型 ofgetUserId是 Observable ofany或任何其他可分配给的类型Recipe

public getUserId(): Observable<Recipe>{
 return this.http.get<Recipe>('...');
}

推荐阅读