Angular 如何访问特定的可观察项目?
我有一个功能:Angular 如何访问特定的可观察项目?,angular,typescript,observable,Angular,Typescript,Observable,我有一个功能: getCategories(): Observable<any> { return this.category.find({where: {clientId: this.userApi.getCurrentId()}}) }; 并且类别id是未定义的 如果我跑步: const source = this.categoryService.getCategories(); const subscribe = source
getCategories(): Observable<any>
{
return this.category.find({where: {clientId: this.userApi.getCurrentId()}})
};
并且类别id是未定义的
如果我跑步:
const source = this.categoryService.getCategories();
const subscribe = source.subscribe(val => console.log(val));
直接输出为:
我想我在某个地方遇到了一个类型问题,但无法解决它
有什么想法吗
感谢并感谢,因为
getCategories()
会返回一个类别数组,而不仅仅是订阅控制台日志中显示的单个类别
您可以尝试以下方法:
const example = source.map((categories) => categories.map((category) => {return category.id}));
问题确实出在类型上。尽可能避免使用“any”,因为这样会失去类型验证的优势 从日志中可以看到,
source
包含一个数组,但您的source.map(Categ=>Categ.id)
将其视为单个对象
最好定义Categ
接口,例如:
interface Categ {
id: string;
categoryName: string;
clientId: string;
}
然后将其用于服务方法:
getCategories(): Observable<Categ[]> {
return this.category.find({where: {clientId: this.userApi.getCurrentId()}})
};
编写接口是否“太多”? My.find()方法来自SDK并返回
Observable
。另外,我在服务中,因为我希望从后端获取数据,并从组件调用此服务。我不知道这项服务是否有用,因为它只涉及这个getCategories()方法。
为了简化,我已经有了一个方法,可以给我分类。我刚刚创建了一个新的设置在服务中。
那么,创建接口是否太多了?您认为呢?您是否绝对确定this.category.find返回一个可观察对象?是的,它作为console.log(可观察对象的源实例)执行;这是真的,谢谢。事实上,我用:const-example=source.map((categories)=>categories.map((category)=>{return-category.id}));
getCategories(): Observable<Categ[]> {
return this.category.find({where: {clientId: this.userApi.getCurrentId()}})
};
const source = this.categoryService.getCategories();
const example = source.map(categ => categ.map(c => c.id));
const subscribe = example.subscribe(val => console.log(val));