Search code examples
angularjsangular-promiseangular-translate

Return string from promise result


I want to have an wrapper function arround this $translate service: https://angular-translate.github.io/docs/#/guide/03_using-translate-service so we can use those function easily in our code by calling $language.translate('keyword') instead of the promise.

So, I create a new service in my app which should do that work. It's a very simple function but it's returning undefined or [Object Object].

 angularApp.factory("$language", ['$translate', function($translate){

    function trans(keyword){
        console.log("translate in $language", keyword);

        return $translate(keyword).then(function(msg) {
            console.log("translation successfull", msg);
            return msg;
        }, function(translationId){
            console.log("translation is not known", translationId);
            return translationId
        })
    }

    return {
        translate : trans
    }
}]);

In both cases, when translation is known or not, the console.log() shows me the right string, but on my page it's showing [object object] or undefined (when I remove the first return right before $translate(keyword). When I use the filter like {{:: "KEYWORD" | translate}} it works fine.

How can I let my function return the string with the translation or the translationId (which is actually the same as the keyword when there is no translation found)?


Solution

  • It seems like you're expecting result to be in synchronous manner, if you're using async variant, anyways it would be going to return Promise object.

    It seem like you could use synchronous variant of $translate service using $translate.instant(), but downside of this sync variant. You won't receive an error code, if anything happens in between translation process.

    Rewrite

    angularApp.factory("$language", ['$translate', '$sce', function($translate, $sce){
    
        function trans(keyword){
            console.log("translate in $language", keyword);
    
            var translation = $translate.instant(keyword)
            var msg = $sce.valueOf(translation);
            if (msg) {
                console.log("translation successfull", msg);
                return msg;
            }
            else {
                console.log("translation is not known");
                return "Error"
            }
        }
    
        return {
            translate : trans
        }
    }]);