我正在建设Angular4网站使用内容CMS API来检索数据。问题是我不能为返回的数据分配正确的类型,即使控制台显示了这些类型。
模拟数据:
export const NAMES: Page[] = content.getEntries({
content_type: 'mainMenu'
}).then(function(response){
response.items.forEach(element => {
return element.fields;
})
});通过控制台返回(如果使用的是console.log ):
Object { title: "About Aliens" }
Object { title: "Portfolio" }
Object { title: "Meet the team" }
Object { title: "Contact us" }以及我用来分配这些数据类型的类:
export class Page {
title: string;
}我刚开始使用Typescript,我想知道我在哪里弄错了,如果有人能指导我从任何API返回这样的数据,我将不胜感激。
谢谢。
发布于 2017-07-25 23:54:54
then调用不返回任何内容,对forEach的调用遍历集合但不返回任何内容。如果你想创建/返回一些东西,你可以使用map,它根据传入的谓词创建一个新的集合。this。解决方法:
export NAMES: IPage[]; // no assignment at this point从某个方法中执行getEntries。
content.getEntries({
content_type: 'mainMenu'
}).then((response) => {
NAMES = response.items.map(element => element as IPage);
});IPage
export interface IPage {
title: string;
}发布于 2017-07-25 23:51:10
使页面类成为类型断言的接口,而不需要实例化,如下所示
export interface Page { title : string }https://stackoverflow.com/questions/45308053
复制相似问题