Reputation: 123
I am building Angular4 website using Contentful CMS API to retrieve data. The problem is I cannot assign the right types for the returned data even thought the console shows those types.
the Mock data:
export const NAMES: Page[] = content.getEntries({
content_type: 'mainMenu'
}).then(function(response){
response.items.forEach(element => {
return element.fields;
})
});
Which is return via the console (If is used console.log ) :
Object { title: "About Aliens" }
Object { title: "Portfolio" }
Object { title: "Meet the team" }
Object { title: "Contact us" }
and the class I use to assign those data types :
export class Page {
title: string;
}
I am new to Typescript and I want to know where I got wrong and I would appreciate it if someone guided me where I can go to master returning such data from any API.
Thank you.
Upvotes: 0
Views: 1946
Reputation: 62298
then
call on the promise does not return anything, a call to forEach
iterates over a collection but returns nothing. If you want to create/return something you could use map
which creates a new collection based on the passed in predicate.this
should you need it.The fix:
export NAMES: IPage[]; // no assignment at this point
Execute getEntries from within some method.
content.getEntries({
content_type: 'mainMenu'
}).then((response) => {
NAMES = response.items.map(element => element as IPage);
});
IPage
export interface IPage {
title: string;
}
Upvotes: 2
Reputation: 514
Make your page class an interface for type assertion without the need for instantiation, like so
export interface Page { title : string }
Upvotes: 0