erasmo carlos erasmo carlos - 1 month ago 7
AngularJS Question

AngularJS: when checking for object null, returning the wrong message

I am adding a couple of alerts for when a record gets updated based on the response of service call.

When I check if there is any data in the response:

if (response.data === null)


This part seems to not be respected and the alert for update on record succeeded gets shown, and if you look in the screen shot, the response.data is null.

I am not sure why the simple if is not working, or if I am looking at the response Object incorrectly.

Can someone please lend a hand so that I can understand the best practice on how to do this?

Thank you.

UPDATED IMAGE

enter image description here

Answer

Hopefully this will help explain why you're not getting the results you're expecting (read comments in code):

function boooooom(msg) {
    alert('We\'re sorry folks! ' + msg);
}

$http({
    method: 'PUT',
    url: 'api/StorePage/PutStorePage?StorePageId=' + this.newpage.StorePageID,
    data: storePage,
})
    .then(
        // This callback will be called when the response is *available*
        function(response) {
            // Change this to `response.data` instead of `!response.data`
            if (response.data) {
                $scope.pages = response.data;
                alert('Congrats!');
            } else {
                boooooom('No data');
            }
        }, 

        // This callback is called if an error occurs or if the server 
        // returns a response with an *error* status.
        //
        // *Your* request hasn't caused an error as it *has* responded 
        // and the response is a 200 status (which is not an error status) 
        // so this callback doesn't get called.
        function(response) {
            boooooom('Houston we have a problem');
        }
    )
    // It looks like you always want to `clearFields` for both failure and success
    // so you can just do that here, which will do that for you.
    .finally(clearFields);
Comments