我有以下错误:
[ts]
Type 'Promise<void>' is not assignable to type 'Promise<IListItem[]>'.
Type 'void' is not assignable to type 'IListItem[]'.
(method) Promise<{
value: IListItem[];
}>.then<void>(onFulfilled?: (value: {
value: IListItem[];
}) => void | Thenable<void>, onRejected?: (error: any) => void | Thenable<void>): Promise<void> (+2 overloads)
在下面的代码中,我缺少什么?
import { SPHttpClient, SPHttpClientResponse } from "@microsoft/sp-http";
import { IWebPartContext } from "@microsoft/sp-webpart-base";
import { IListItem} from "./models/IListItem";
import { IFactory } from "./IFactory";
import { INewsListItem } from "./models/INewsListItem";
import { IDirectoryListItem } from "./models/IDirectoryListItem";
import { IAnnouncementListItem } from "./models/IAnnouncementListItem";
export class ListItemFactory implements IFactory {
private _listItems: IListItem[];
public getItems(requester: SPHttpClient, siteUrl: string, listName: string): Promise<IListItem[]> {
switch(listName) {
case "GenericList":
let items: IListItem[];
// tslint:disable-next-line:max-line-length
return requester.get(`${siteUrl}/_api/web/lists/getbytitle('${listName}')/items?$select=Title,Id,Modified,Created,Author/Title,Editor/Title&$expand=Author,Editor`,
SPHttpClient.configurations.v1,
{
headers: {
"Accept": "application/json;odata=nometadata",
"odata-version": ""
}
})
.then((response: SPHttpClientResponse): Promise<{ value: IListItem[] }> => {
return response.json();
})
.then((json: { value: IListItem[] }) => {
console.log(JSON.stringify(json.value));
items=json.value.map((v,i)=>({
key: v.id,
id: v.id,
title: v.title,
created: v.created,
createdby: v.Author.Title,
modified: v.modified,
modifiedby: v.Editor.Title
}));
更新1:
上述方法的消费者:
// read items using factory method pattern and sets state accordingly
private readItemsAndSetStatus(): void {
this.setState({
status: "Loading all items..."
});
const factory: ListItemFactory = new ListItemFactory();
factory.getItems(this.props.spHttpClient, this.props.siteUrl, this.props.listName)
.then((items: IListItem[]) => {
const keyPart: string = this.props.listName === "GenericList" ? "" : this.props.listName;
// the explicit specification of the type argument `keyof {}` is bad and
// it should not be required.
this.setState<keyof {}>({
status: `Successfully loaded ${items.length} items`,
["Details" + keyPart + "ListItemState"] : {
items
},
columns: buildColumns(items)
});
});
}
答案 0 :(得分:3)
您的then
回调分配给全局items
变量,但不会返回任何值 - 因此承诺会以undefined
结算。你需要使用
.then((json: { value: IListItem[] }) => {
console.log(JSON.stringify(json.value));
return json.value.map((v,i) => ({
// ^^^^^^
key: v.id,
id: v.id,
title: v.title,
created: v.created,
createdby: v.Author.Title,
modified: v.modified,
modifiedby: v.Editor.Title
}));
});