试图访问 angular 中的对象数据 6 属性 类型对象中缺少 id
trying to access object data in angular 6 property id is missing in type object
我创建了一个如下所示的界面:-
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[]
,您需要确保 return 类型的 getUserId
是 any
的 Observable 或任何其他可分配给 Recipe
。
public getUserId(): Observable<Recipe>{
return this.http.get<Recipe>('...');
}
我创建了一个如下所示的界面:-
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[]
,您需要确保 return 类型的 getUserId
是 any
的 Observable 或任何其他可分配给 Recipe
。
public getUserId(): Observable<Recipe>{
return this.http.get<Recipe>('...');
}