简体   繁体   中英

How to check if data returned from a promise is empty

I have the following, very simplified snippet:

c.then(function(data){
    vm.checkedOut = data;
});

It will either return a record, or it will not. Either way, the promise does return an object--it just might not have any record data attached.

So far, so good. Here's my question: how can I detect recordless responses in my views?

I was doing this:

<div ng-if="vm.checkedOut.loaneeName !== undefined">
    checked out!
</div>

loaneeName is a property of the record and it will be undefined if no record is returned. Kind of sloppy, but it works.

However this was how I displayed the opposite message:

<div ng-if="vm.checkedOut.loaneeName === undefined">
    not checked out!
</div>

Because vm.checkedOut.loaneeName will always be undefined when the page first loads (and waiting for responses from the API), the "not checked out!" message appears, at least for a while, which could be very bad if the connection speed is slow enough.

To fix this issue, I've done the following:

    c.then(function(data){
        vm.checkedOut = data;
        if(vm.checkedOut.loaneeName === undefined){
            vm.forRealsCheckedOut = true;
        }
        else {
            vm.forRealsCheckedOut = false;
        }
    });

And then:

<div ng-if="vm.forRealsCheckedOut === false">
    not checked out!
</div>
...

This works, but it also strikes me as a slightly gross workaround for what I assume should be a common problem.

I am not the first person to ask a question like this, but I don't have an array and other answers aren't much help .

Is there a better way?

The basis of your problem is that if the connection is slow, then the "not checked out!" message will appear until the data is loaded. You need to detect when the data is actually loaded. You can do that by checking if vm.checkedOut is defined or not:

<div ng-if="vm.checkedOut !== undefined && vm.checkedOut.loaneeName === undefined">
    not checked out!
</div>

Only if vm.checkedOut is defined AND vm.checkedOut.loaneeName is defined will you see the "not checked out" message.

Or you could add a flag variable in your .then() function which will signal the ng-if statements that the data has been loaded and they can begin checking for the loaded values:

$scope.dataLoaded = false;

c.then(function(data){
    vm.checkedOut = data;
    $scope.dataLoaded = true;
});

<div ng-if="dataLoaded && vm.checkedOut.loaneeName === undefined">
    not checked out!
</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