Created by @Damo in Q&As
@Damo
@Damo

Hi, is possible get payload (json) or response code (404,...)?

.then(payload => { // payload is undefined });

I want to remove js eventlistener when success and to keep when is fail.

@jahudka
@jahudka

Hi, sorry, no - page.open() doesn't necessarily correspond to a single HTTP request, but rather a page transaction, which could under the hood mean anything from zero to multiple (serial or parallel) HTTP requests, so it doesn't make any sense to expose the payload or response from the usual single request. That being said, depending on your exact situation, you can either:

di.getService('page').open(...).then(onSuccess, onFail)

which would call onSuccess after the entire page transaction (including any transition animations) finishes, or onFail if there was an error (which would happen if the backend responds with e.g. a 404, but again, only after animations are finished). Or you can write a custom transaction agent, which is basically any service which hooks into the page transaction events - take a look at e.g. the AjaxAgent service, which is what Nittro uses under the hood to dispatch and handle AJAX requests during a page transaction - in short, you'd write a service which listens for the transaction-created event of the page service and in the handler you'd attach listeners to events occuring on the Transaction object during the transaction, e.g. like this:

var MyAgent = _context.extend(function(page) {
    this._ = {
        page: page,
    };

    this._.page.on('transaction-created', this._handleTransaction.bind(this));
}, {
    _handleTransaction: function(evt) {
        // bind to the 'ajax-response' event
        // emitted on the Transaction by the AjaxAgent:
        evt.data.transaction.on('ajax-response', this._handleResponse.bind(this));
    },
    _handleResponse: function(evt) {
        console.log(evt.data.response.getPayload());
    }
})
@Damo
@Damo

i have a problem with "bind". When I switch handler to function then handleTransaction is called, but event "ajax-response"" is dead, the event is not triggered.

(index):322 Uncaught TypeError: Cannot read properties of undefined (reading 'bind') at _context.extend._handleTransaction((index):322:89)

di.getService('page').on("transaction-created", function(evt) {
                    // event triggered    
                    console.log(evt);
                    evt.data.transaction.on('ajax-response', function(evt) {                       
                        //event is not triggered
                        console.log(evt);
                    });
                });
@Damo
@Damo

aáá, ajax-response is called when ajax is success, but not if is failed (404)

@Damo
@Damo

Perfect, For error I used event "abort error"

Thanks

@Damo
@Damo

This solution opens the listening event forever. How can I stop or assign to only one page.open?

Sign in to post a reply