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.
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;
}
使您的页面类成为类型声明的接口,而无需实例化,就像这样
export interface Page { title : string }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.