【问题标题】:Unknown provider error for filter in AngularJS ES6 syntaxAngularJS ES6 语法中过滤器的未知提供程序错误
【发布时间】:2018-03-22 09:49:06
【问题描述】:

捆绑并部署到远程服务器后,我无法在我的应用中使用过滤器。它在本地运行良好,但如果我远程运行我的应用程序,我会收到错误:

"Error: [$injector:unpr] Unknown provider: eProvider <- e <- filterByQueryFilter"

这是我的代码:

app.js:

import myFilters from "./shared/filters";
import myModule from "./myModule";

export default angular.module('app', [
    lots-of-modules...,
    myFilters,])
    .config(defaultRouting)
    .run(["$http", "$rootScope", "$state", function($http, $rootScope, $state){ //code.. }]);

index.js(在 shared/filters 文件夹中):

import filterByQuery from "./filterbyquery.filter.js";
import highlightQuery from "./highlightquery.js";
import dateFormatter from "../formatter/dateFormatter";

export default angular.module("my.filters", [])
    .filter("filterByQuery", filterByQuery)
    .filter("highlightQuery", highlightQuery)
    .filter("dateFormatter", dateFormatter)
    .name;

another-module.js(我尝试使用过滤器的地方):

export default class anotherModule{

    constructor() {
        this.restrict = 'E';
        this.replace = false;
        this.template = require('./template.html');

        this.scope = {};

        this.controller = AnotherModule;
        this.controllerAs = 'ctrl';
    }
}

class AnotherModule{
    constructor($scope, $filter) {
        this.$filter = $filter;
    }
}

AnotherModule.$inject = [..., "$filter"];

在控制器中使用过滤器:

res = this.$filter("filterByQuery")(res, this.filterString);

考虑到它在本地运行良好,我不确定我在这里做错了什么。此外,highlightQuery 过滤器通过使用template.html 中的管道语法来工作

有人知道这里发生了什么吗?

【问题讨论】:

    标签: javascript angularjs ecmascript-6 angular-filters


    【解决方案1】:

    缩小的 AngularJS 应用程序应该是 properly annotated 以便执行依赖注入。

    filterByQuery 过滤器工厂函数没有注释。由于它包含在单独的文件中,因此使用 $inject 注释将其保存在与函数本身相同的模块中是有意义的。是John Papa style guide提出的带有ES模块的ES6中最好的注解方式

    【讨论】:

    • 我忘了把它添加到我的问题中,但我将$filter 注入AnotherModule,如下所示:AnotherModule.$inject = [..., "$filter"]。我以为 $filter 是过滤器提供者,所以它不需要单独注入我想要使用的过滤器?
    • 通过将过滤器代码移动到实际需要它的模块中使其工作(在其他任何地方都不需要)。这符合 John Papa 规则,即不让过滤器扫描对象的所有属性。不过感谢您的帮助。
    • 不客气。 eProvider <- e <- filterByQueryFilter 错误是因为 $filter 将 filterByQuery filter 注册为 filterByQueryFilter service 在内部,通过在过滤器名称中添加Filter 后缀(您可以检查它在框架源中的工作方式)。
    • 嗯。我还尝试通过执行$filter('filterByQueryFilter')() 来使用过滤器,但它只是在错误消息中添加了另一个过滤器(eProvider <- e <- filterByQueryFilterFilter)。
    • 你不需要做这样的事情,至少在生产中是这样。当您在模板中使用filterByQuery 时,编译器会像$injector.get('filterByQueryFilter') 一样得到它,这就是它的工作原理,这就是为什么错误提到它就像filterByQueryFilter
    猜你喜欢
    • 2020-01-29
    • 1970-01-01
    • 2015-11-05
    • 2016-01-26
    • 2023-03-26
    • 2016-04-01
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多