简体   繁体   中英

Angular filter service with promise

i have the following filter:

    app.filter("findDivision", function(divisionService) {

    var isWaiting = false;
    var returnValue = null;

    function myFilter(input) {

        var translationValue = "Loading...";
        if(returnValue)
        {
            translationValue = returnValue;
        } else {
            if(isWaiting === false) {
                isWaiting = true;
                divisionService.getDivisionById(input).then(function(data) {
                    console.log("GetTranslation done");
                    returnValue = data[0].name;
                    isWaiting = false;
                });
            }
        }

        return translationValue;
    }

    return myFilter;
});

Where the function i call in divisionService looks like this:

 getDivisionById: function (id) {
    var d = $q.defer();
    $http({
        url: api.getUrl2('division'),
        method: "GET",
        params: {filters: {id: {EQUAL: id}}}
    }).success(function (data, status, headers, config) {
        d.resolve(data);
    }).error(function (data, status, headers, config) {
        api.handleError(data);
        console.log(data);
        d.reject(data);
    });
    return d.promise
}

Sadly the output of this looks like this:

在此处输入图片说明

Can anyone tell me why this is happening? and how i can get the correct value?

Upon the first calls to the filter, the promise probably hasn't resolved yet, because the HTTP call takes a while to finish. Your filter code will immediately jump to the return statement return translationValue; . In this case, the filter returns "Loading...".

Unfortunately, the filter won't automatically re-evaluate the filter until the next digest cycle. Angular has no way of knowing that it should do another digest cycle, because nothing changes (no user interaction or changes to $scope). As an experiment, try to manually trigger a digest cycle by changing the model, eg by using an input box with ng-model . At that moment, you will see the filter will re-evaluate and the output will be shown.

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