简体   繁体   中英

Return a q.promise - knockout/app

I'm building a mobile app that calls an API. An endpoint of the API gets called on app login and I see the results load in the DOM. I want to defer or promise the output/result for when I then click on a button to open another view/page inside the app. At the moment the app loads the endpoint twice when the API is called at the beginning and on the tap of the button to open up the desired page view.

The problem I am having is getting the result packaged as a promise and then sent to the viewmodel ready for knockout to pass to my view.

The promise services the app uses are "q" and also has "promisehelper". Not familiar with any and how I should be using them.

Dataservice.js runs at app load - (this calls a function that builds the endpoint of the API)

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

Viewmodel.js - (needs to call the promise from the data service)

        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 - displays result on page/view

<section class="help-text">
<div class="flex-container">

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

</div>

You can just put returned data to the MyText and use "if" and "ifnot" bindings in the markup:

Code:

   var MyText = ko.observable();

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

Markup:

<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>

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