如何在角度2中的promise中返回值

时间:2018-03-07 23:56:14

标签: angular promise angular2-services angular-promise session-storage

我想检查一个值的sessionStorage(sessionStorage ['new']),如果它存在,我想返回它并忽略函数的其余部分,但是我得到一个错误,然后没有定义。我不确定我做错了什么。

public getDispositionTree(memberType: string,
                          market: string,
                          includeFiltered: boolean = false,
                          forcedUUIDS: string[] = [],
                          includeArchived: boolean = false): 
    Promise<DispositionTreeNode[]> {

    let treeLoadedPromise;

    if (this.savedDispositionTrees.has(market)) {
        treeLoadedPromise = Promise.resolve();
    } else {
        // **THIS LINE BELOW IS MY CHANGE**
        treeLoadedPromise = sessionStorage['new']
        // treeLoadedPromise = this.loadDispositionTree(market);
    }
    return treeLoadedPromise.then(() => {
        if (includeFiltered) {
            if (includeArchived) {
                return this.savedDispositionTrees.get(market);
            } else {
                return this.getExcludeArchivedDispositionTree(this.savedDispositionTrees.get(market));
            }

        }
        return this.getRelevantDispositionTree(market, memberType, forcedUUIDS);
    });
}

这是错误:

 core.es5.js?0445:1085 ERROR Error: Uncaught (in promise): TypeError: 
 treeLoadedPromise.then is not a function
 TypeError: treeLoadedPromise.then is not a function

1 个答案:

答案 0 :(得分:0)

错误并未声明then未定义。

您要将treeLoadedPromise设置为sessionStorage["new"]返回的内容。这个值不是一个承诺。如果该项目存在,则返回一个字符串,否则为undefined

我猜你想要这样的东西:

let treeLoadedPromise;

if (this.savedDispositionTrees.has(market)) {
    treeLoadedPromise = Promise.resolve();
} else {

    let sessionStorageValue = sessionStorage['new'];
    if (sessionStorageValue !== undefined)
    {
        treeLoadedPromise = Promise.resolve(sessionStorageValue);
    }
    else
    {
        treeLoadedPromise = this.loadDispositionTree(market);
    }
}