Return一个q.promise - knockout/app

Return a q.promise - knockout/app

我正在构建一个调用 API 的移动应用程序。 API 的端点在应用程序登录时被调用,我在 DOM 中看到结果加载。我想推迟或承诺 output/result,然后单击一个按钮在应用程序中打开另一个 view/page。目前,当开始调用 API 时,应用会加载端点两次,然后点击按钮打开所需的页面视图。

我遇到的问题是将结果打包为 promise,然后发送到视图模型,准备好进行剔除以传递到我的视图。

应用程序使用的承诺服务是"q",还有"promisehelper"。不熟悉任何以及我应该如何使用它们。

Dataservice.js 在应用加载时运行 -(这会调用构建 API 端点的函数)

 function getHelpText(companyName, userName, password) {
        return q.when(home.helpTextGet(company.name, company.userName, company.password));
    }

Viewmodel.js - (需要从数据服务调用promise)

        var MyText = ko.observable();

        var company = shell.authenticatedCompany();
        return q.getHelpText()
            .then(function(data) {
                if (!data) {
                    MyText(document.getElementById('no-help').innerHTML = '<div class="flex-item"><p>Request help from home Support:<br /><a href="mailto:support@home.com" class="low-profile-btn btn btn-lg"><i class="fa fa-info-circle"></i>&nbsp;Contact Home Support</a></p></div>');
                } else {
                    MyText(data);
                }
            });
        return {
            MyText: MyText
        };
        });

View.html - 在 page/view

上显示结果
<section class="help-text">
<div class="flex-container">

    <div id="no-help" class="help-content" data-bind="html: MyText"></div>

</div>

您可以只将返回的数据放入 MyText 并在标记中使用 "if" 和 "ifnot" 绑定:

代码:

   var MyText = ko.observable();

    var company = shell.authenticatedCompany();
    return q.getHelpText()
        .then(function(data) {
            MyText(data);
        });
    return {
        MyText: MyText
    };
    });

标记:

<section class="help-text">
<div class="flex-container">
    <!-- ko if: MyText -->
    <div id="no-help" class="help-content" data-bind="html: MyText"></div>
    <!-- /ko -->
    <!-- ko ifnot: MyText -->
    <div id="no-help" class="help-content">
    <div class="flex-item">
        <p>Request help from home Support:<br />
        <a href="mailto:support@home.com" class="low-profile-btn btn btn-lg"><i class="fa fa-info-circle"></i>&nbsp;Contact Home Support</a>
        </p>
    </div>
    </div>
    <!-- /ko -->
</div>