【问题标题】:Unknown Provider Error when using $filter service使用 $filter 服务时出现未知的提供程序错误
【发布时间】:2016-11-08 22:11:50
【问题描述】:

我正在使用 Ionic 框架创建一个混合应用程序,并设置了一个工厂来保存一组对象。我想使用 $filter 服务来抓取数组中具有特定 ID 的对象。这是我现在拥有的代码。我从这个堆栈溢出问题中得到了这个实现的想法:In Angular, I need to search objects in an array

angular.module('prototype.services', [])

.factory('Patients', function($filter) {

var currentID;
var currentPatient = $filter('patientFilter')(patients, {id: currentID}, true);


var patients = [{
id: 1,
name: 'Alexander Hamilton'
}];



return {

all:function() {
    return patients;
},

add: function(patient) {
    patients.push( {
        name: patient.name
    })
},

setID: function(id) {
    currentID = id;
},

getID: function() {
    return currentID;    
},


};



});

据我了解,这应该可以工作,因为我将 $filter 注入了我创建的工厂。我对 Angular 很陌生,所以我可能缺少一些明显的东西。

完全错误是:

ionic.bundle.js:26794 Error: [$injector:unpr] Unknown provider:     patientFilterFilterProvider <- patientFilterFilter <- Patients
http://errors.angularjs.org/1.5.3/$injector/unpr?    p0=patientFilterFilterProvider%20%3C-%20patientFilterFilter%20%3C-%20Patients
at ionic.bundle.js:13438
at ionic.bundle.js:17788
at Object.getService [as get] (ionic.bundle.js:17941)
at ionic.bundle.js:17793
at Object.getService [as get] (ionic.bundle.js:17941)
at ionic.bundle.js:32697
at Object.<anonymous> (services.js:6)
at Object.invoke (ionic.bundle.js:17995)
at Object.enforcedReturnValue [as $get] (ionic.bundle.js:17834)
at Object.invoke (ionic.bundle.js:17995)

【问题讨论】:

  • 你在缩小你的代码吗?
  • @SteamDev 我不相信我是,而且我对角度或离子没有太多经验来看看我是否是。但是,我确实将工厂语句更改为 .factory('Patients' , ['$filter', function($filter) { 以防万一,但我仍然收到错误。
  • 能否包含定义患者过滤器的代码?

标签: angularjs filter ionic-framework runtime-error


【解决方案1】:

您的代码假设有一个patientFilter 附加到您的模块:

angular.module('prototype.services', [])

.filter('patientFilter', function(){/*...*/}) // doesn't exist, so unknown provider errors

您可能想要做的是以下...

angular.module('prototype.services', [])

.factory('Patients', function($filter) {

    var currentID;
    var patients = [{
        id: 1,
        name: 'Alexander Hamilton'
    }];

    return {

      // ... other factory methods ...

      getCurrentPatient: function(){
        var currentPatient = $filter('filter')(patients, { // use generic 'filter' filter
            id: currentID
        }, true);

        return currentPatient || patients[0];
      }
    }
});

【讨论】:

  • 这修复了错误!谢谢你向我解释这一切。如果你不介意你能解释一下为什么你返回 currentPatient ||患者[0] 而不是当前患者? currentPatient 不会持有“通过”过滤器的对象吗?
  • 如果currentID 尚未设置,或者currentID 与数组中的任何项目都不匹配,则currentPatient 可能为空或未定义。只是一个安全网,以防 currentPatient 是虚假值。
猜你喜欢
  • 1970-01-01
  • 2015-05-05
  • 2016-06-14
  • 2017-08-10
  • 1970-01-01
  • 1970-01-01
  • 2016-12-07
  • 2015-10-11
  • 2020-02-29
相关资源
最近更新 更多