【问题标题】:AngularJS Promise & atop Filter. Failed to execute 'atob' on 'Window'AngularJS Promise & 在过滤器之上。无法在“窗口”上执行“atob”
【发布时间】:2015-03-18 00:26:25
【问题描述】:

背景: 从事 Angular 前端工作。从后端检索 base64 编码的文档。 atob 给了我一个错误,但一切正常。

怀疑:我认为我的 atob 过滤器被调用了两次。在变量未定义/为空时点击承诺,然后在承诺填充变量之后。

过滤代码

angular.module('docFilters', []).filter('base64Decode', function() {
    return function(cipherText) {
        return atob(cipherText);
    };
});

控制器代码

angular.module('doc')
    .controller('DocCtrl', ['$scope', 'DocService', function ($scope, DocService) {   
        $scope.doc = DocService.getCurrentDoc();    
    }]);

getCurrentDoc() 是一个 REST 请求。它向内部 Web 服务发出 GET 请求。

HTML

<span ng-bind-html="doc.content | base64Decode"></span>

这工作“很好” - 不检查你永远不会知道的控制台。控制台显示:

“错误:在'Window'上执行'atob'失败:要解码的字符串没有正确编码。”

这对我来说是新的,所以我不确定是否有更好的方法。

【问题讨论】:

    标签: javascript angularjs angularjs-scope promise angular-promise


    【解决方案1】:

    atob(undefined); //throws an error

    你需要修改你的过滤器

    angular.module('docFilters', []).filter('base64Decode', function() {
        return function(text) {
            return text && atob(text);
        };
    });
    

    【讨论】:

    • 我选择了这个。也许是因为我是新手,但这看起来很优雅,是那种让我回到系统编程的代码。这类似于三元运算符吗?取文本,直到变量被promise填充,然后解码密文?
    • @HayekSplosives A &amp;&amp; B 本质上的意思是“如果 A 则 B 否则 A”。
    • @HayekSplosives 由于&amp;&amp; 运算符的“懒惰”,它可以工作。考虑A &amp;&amp; B 如果A 是假的,你不需要评估B,否则你需要检查B 是否是真的。您可以使用三元运算符return A ? B : A 重写它。
    【解决方案2】:

    为什么不让过滤器检查是否有值?

    angular.module('docFilters', []).filter('base64Decode', function() {
        return function(cipherText) {
            if (cipherText) {
                return atob(cipherText);
            }
        };
    });
    

    【讨论】:

    • 因为我还是新手,所以我不知道该怎么做。我理解这个概念,但不理解实现。泰!
    猜你喜欢
    • 2014-04-29
    • 2021-03-25
    • 2020-09-15
    • 1970-01-01
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多