简体   繁体   中英

Angular Promise<void>' is not assignable to type

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.

  1. You are trying to assign a promise to an array, you have to do the assignment in the callback of the promise.
  2. Your 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.
  3. Use an arrow function for the promise callback so you have a reference to this should you need it.
  4. There is no need to make Page a concrete type, use an interface instead so you can use casting. You only need a concrete type if you are going to add behavior but if its just a plain old object that is deserialized from json use an interface.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM