Reputation: 689
I have a function:
getCategories(): Observable<any>
{
return this.category.find({where: {clientId: this.userApi.getCurrentId()}})
};
where this.category.find return type is Observable<T[]>
.
I call getCategories() with:
const source = this.categoryService.getCategories();
const example = source.map(Categ=> Categ.id);
const subscribe = example.subscribe(val => console.log(val));
and Categ.id is undefined
If I run:
const source = this.categoryService.getCategories();
const subscribe = source.subscribe(val => console.log(val));
I think I have a type problem somewhere but cannot figure it out.
Any idea ?
Thanks and Regards,
Upvotes: 1
Views: 89
Reputation: 690
As an array of categories is returned by the getCategories()
and not just a single category as is evidenced by your subscribe's console log.
You could try something like:
const example = source.map((categories) => categories.map((category) => {return category.id}));
Upvotes: 1
Reputation: 689
Is writing an interface something "too much"?
My .find() method is coming from a SDK and returning Observable<T[]>
. Also, I am in a service because I would like to get data from the back-end and call this service from a component. I have no idea if this service has a use as it is about only this getCategories() method.
To simplify, I already have a method that gives me categories. I just created a new one to set it in the service.
So is creating an interface too much? What do you think?
Upvotes: 0
Reputation: 6726
The problem is indeed with the types. You should avoid using "any" when possible because then you loose advantage of type validation.
From the log it is visible that the source
contains an array but your source.map(Categ=> Categ.id)
treats it as single objects.
It would be better to define Categ
interface, e.g.:
interface Categ {
id: string;
categoryName: string;
clientId: string;
}
Then use it for service method:
getCategories(): Observable<Categ[]> {
return this.category.find({where: {clientId: this.userApi.getCurrentId()}})
};
so later compiler can help you to spot the problem and fix the code:
const source = this.categoryService.getCategories();
const example = source.map(categ => categ.map(c => c.id));
const subscribe = example.subscribe(val => console.log(val));
Upvotes: 1