無法從控制器訪問工廠中的AngularJS功能

[英]AngularJS functions in the factory cannot be accessed from the controller


Im new to angular js. Can anyone please tel me why i get an error saying functions in the factory cannot be accessed from the controller.

我是角度js的新手。任何人都可以打電話給我,為什么我得到一個錯誤,說無法從控制器訪問工廠中的功能。

Error: UserService.getAllCustomers is not a function

錯誤:UserService.getAllCustomers不是函數

This happens when I add

添加時會發生這種情況

  App.service('UserService', function () { })

to the controller. If this is not added it gives

到控制器。如果沒有添加,則給出

Error: [$injector:unpr] Unknown provider:serServiceProvider<-UserService<- UserController

錯誤:[$ injector:unpr]未知提供者:serServiceProvider <-UserService < - UserController

2 个解决方案

#1


0  

You should have someting like :

你應該喜歡:

angular.module('MyApp')
    .factory('serviceName',[
        function () {
            return function () {
                /*your code */
            };
         }]);


angular.module('MyApp')
    .controller('controllerName',['serviceName'
        function (serviceName) {

         }]);

#2


0  

The userService does not have the "getAllCustomers"

userService沒有“getAllCustomers”

  var App= angular.module('myApp', []);

    App.controller("MyCtrl", ['UserService', function(UserService) {
      UserService.getAllCustomers();
    }]);

    App.service('UserService', function() {
      this.getAllCustomers = function() {
        alert('getAllCustomers');
      }
    });

DEMO

Note: If you removed "UserService" from the app ,so the UserService is not available in the app, but you are injected in controller then angular will check UserService is created or not, if it is not created it will throw the error like Error:

注意:如果您從應用程序中刪除了“UserService”,那么UserService在應用程序中不可用,但您注入控制器然后angular將檢查UserService是否已創建,如果未創建它將拋出錯誤,如Error :

[$injector:unpr] Unknown provider:serServiceProvider<-UserService<- UserController

[$ injector:unpr]未知提供者:serServiceProvider <-UserService < - UserController


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/08/09/729c2801d9aa8d71ed6621aef3e8409f.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com