且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

服务注入到控制器

更新时间:2023-02-12 11:01:54

当您使用工厂你必须返回的东西。你只是定义了一堆方法有,但他们没有提供给任何人。

这也是很好用不同的命名约定。例如,而不是LogsController的,使用LogsCtrl。 AngularJS追加控制器内部和你可能最终,在异国情调的情况下,处理像LogsControllerController的名字。

使用工厂并返回服务的简化方式:

  VAR ListLogsModule = angular.module(对myApp,[]);ListLogsModule.factory('ListLogsSrv',函数($ HTTP){
    //首先定义服务(您使用的是工厂)
    VAR的getData =功能(){
        返回哎; //物品;
    };    //然后返回。
    //提供使用内部的getData一个公共方法的getData()
    返回{
        的getData:的getData
    }
});ListLogsModule.controller(ListLogsCtrl功能($范围,ListLogsSrv){
    $ scope.w =世界;
    $ scope.logs = ListLogsSrv.getData();
});

您也可以在工厂的 $ HTTP 请求。这意味着,当你实例化的服务,你会触发异步请求(当它被用于第一次),所以没有人会等待它完成,你会得到未定义
如果您在控制器使用这项服务,你可能需要决心的承诺。

使用承诺的一个例子:

  VAR承诺= $ q.defer();
变种thisPageNumber = 1;
...
VAR的baseUrl ='../Api/LogApi/GetLogsByPage';
...
答应= $ http.get(...

现在你可以在控制器中使用这个承诺,例如,或在你的服务的方法。

我前两天回答了相关的问题Angular服务认定中的:服务器或工厂

I am new to Angular. I have a simple web page, but the codes for controller are not working. It seems I do not call or inject service "ListLogsFactory" in the controller properly. Please help. Thank you.

My codes include a module, service, and controller that all declared/defined as follows:

    var myApp = angular.module("ListLogsModule", []);


    myApp.factory('ListLogsFactory', function ($http) {
            var thisPageNumber = 1;
            var thisPageSize = 10;
            var baseUrl = '../Api/LogApi/GetLogsByPage';

            var items = {};

            $http({
                method: 'GET',
                url: baseUrl,
                data: $.param({ pageNumber: thisPageNumber, pageSize: thisPageSize })
            })
            .success(function (data, status, headers, config) {
                items = data;
                console.log(items);
            })
            .error(function (data, status, headers, config) {
                alert('error: ' + status);
            });

            function getData() {
                return items;
            }
    });

    // The error is seen in FireFox and happens in the controller code:
    myApp.controllers.ListLogsController = function ($scope, ListLogsFactory) {
       $scope.logs = ListLogsFactory.getData(); // NOTE: this line throws error on running with something like "ListLogsFactory" is undefined
   }

When you use factory you have to return something. You're just defining a bunch of methods there but they aren't available to anybody.

It's also good to use a different naming convention. For example, instead of LogsController, use LogsCtrl. AngularJS appends "Controller" internally and you might end up, in exotic situations, handling names like "LogsControllerController".

A simplified approach of using factory and returning the service:

var ListLogsModule = angular.module("myApp", []);

ListLogsModule.factory('ListLogsSrv', function ($http) {
    // first define the service (you're using a factory)
    var getData = function() {
        return "hey";//items;
    };

    // then return it.
    // offer a public method "getData" that uses your internal getData()
    return {
        getData : getData
    }
});

ListLogsModule.controller("ListLogsCtrl", function ($scope, ListLogsSrv) {
    $scope.w = "world";
    $scope.logs = ListLogsSrv.getData(); 
});

You also have an $http request in the factory. That means that you'll trigger the async request when you instantiate the service (when it is used for the first time), so nobody will wait for it to finish and you'll be getting undefined. If you are using this service in a controller, you will probably need to resolve a promise.

An example of using a promise:

var promise = $q.defer();
var thisPageNumber = 1;
...
var baseUrl = '../Api/LogApi/GetLogsByPage';
...
promise = $http.get(...

Now you can use this promise in the controller, for example, or in the methods of your service.

I answered a related question two days ago Angular Service Defination: server or factory