typescript - 类型对象中缺少尝试访问角度 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]}
知道有什么问题吗?
解决方案
因为likes$
是Recipe[]
,您需要确保返回类型 ofgetUserId
是 Observable ofany
或任何其他可分配给的类型Recipe
。
public getUserId(): Observable<Recipe>{
return this.http.get<Recipe>('...');
}
推荐阅读
- azure-devops - Reusing PowerShell Scripts in Azure DevOps
- c++ - 如何让 clang 格式在参数中间而不是括号后中断?
- python - 将文件的十六进制内容转换为base64并打印结果
- javascript - 从 requirejs 迁移到 es6 导入
- python - Matplotlib pyplot crush a ladder python
- excel - Powershell测试excel单元格是否为边框
- c++ - 在 C(或 C++)中分配大于 2GB 的数组
- c# - 重复 RDLC ReportViewer 子报表
- c# - How do I run .cs tests that I normally run in the Visual Studio Test Explorer, in the command line?
- oracle - 在 oracle apex 5.0 中上传文件是否有大小限制?