我如何在“解决"中使用工厂?$stateProvider 的? [英] How can I use a factory inside a "resolve" of $stateProvider?

查看:27
本文介绍了我如何在“解决"中使用工厂?$stateProvider 的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为标题我想用一个工厂insisde一个解决"app.js:

 角度.module("goHenry", ["ui.router"]).factory("httpPost", httpPost).controller("MainCTRL", ["$scope", MainCTRL]);函数 MainCTRL($scope, httpPost){this.nameApp = "CiaoMiao";console.log($scope.children, httpPost);}函数 httpPost($http, $q){返回 {得到:函数(){var deferred = $q.defer();$http.post.apply(null, 参数).success(deferred.resolve).错误(延期.解决);返回 deferred.promise;}}//返回}

routers.js:

 var httpConfig = {headers:{ "Content-Type" : "application/x-www-form-urlencoded" }};var config = ["$urlRouterProvider", "$stateProvider", function($urlRouterProvider, $stateProvider){$urlRouterProvider.otherwise("/");$stateProvider.state(多",{网址:/多",viewA@multi":{templateUrl: "app/templates/login.htm",控制器:[$scope",getChildrenNumber",函数($scope,getChildrenNumber){this.nameApp = "nameAppChanged";this.gatto = "苗";}],控制器为:ctrl"}},解决: {getChildrenNumber: ["$http", function($http, httpPost){var httpP = httpPost.get("http://domain.com/user/login/api-login", $.param({ username:"ciaociao6@ciao.com", password:"ciaociA0" }), httpConfig)控制台日志(httpP);返回来自 API 的一些响应";}]}});有角的.module("CiaoMiao").config(config);

由于console.log 我得到未定义",我不知道如何在这部分代码中注入该工厂.我尝试放入该视图的主控制器中,但效果不佳.

解决方案

(如果您将解决方案放在您的视图中,它应该可以工作.如果您需要在同一状态的多个视图中解决该问题.我会尝试使用抽象状态并在那里添加解析.)有效但不需要(请参阅下面的编辑.)

请查看这个 jsfiddle 或下面的演示.

为了让内容更易于阅读,我对演示进行了一些精简.演示中也没有为 DI 添加数组符号.您不需要在工厂中使用延迟对象,因为 $http 已经返回了一个承诺.

您可以将解析放在视图之外,它也应该可以工作.我已经在这个 fiddle 中试过了.因此,您的代码中可能存在不同的问题.

好的,我认为您的代码的问题在于您没有从您的承诺中返回已解决的值.类似 promise.then(function(response) {return response;});

angular.module('demoApp', ['ui.router']).factory('myDataFactory', 函数 ($http) {返回 {得到:函数(id){返回 $http.post('http://crossorigin.me/http://www.mocky.io/v2/55a65562b2016ce10c7e6ea9', {身份证:身份证}).then(函数(响应){返回响应;});}};}).config(function ($urlRouterProvider, $stateProvider) {$urlRouterProvider.otherwise('/124');$stateProvider.state('home', {网址: '/:id',意见:{'视图A':{模板:'{{hello}}',控制器:'homeController',解决: {后端数据:函数(myDataFactory,$stateParams){返回 myDataFactory.get($stateParams.id);}}},'@':{模板:'主视图'}}});}).controller('homeController', function ($scope, backendData) {控制台日志(后端数据);$scope.hello = backendData;});

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js"></script><div ng-app="demoApp"><div ui-view=""></div><div ui-view="viewA"></div>

As title I want to use a factory insisde a "resolve" app.js:

    angular
    .module("goHenry", ["ui.router"])
    .factory("httpPost", httpPost)
    .controller("MainCTRL", ["$scope", MainCTRL]);

function MainCTRL($scope, httpPost){
    this.nameApp = "CiaoMiao";
    console.log($scope.children, httpPost);
}

function httpPost($http, $q){
    return {
        get: function() {
             var deferred = $q.defer();
             $http.post.apply(null, arguments)
                       .success(deferred.resolve)
                       .error(deferred.resolve);
         return deferred.promise;
        }
    }//RETURN
}

routers.js:

    var httpConfig = {headers:{ "Content-Type" : "application/x-www-form-urlencoded" }};

    var config = ["$urlRouterProvider", "$stateProvider", function($urlRouterProvider, $stateProvider){

        $urlRouterProvider.otherwise("/");

        $stateProvider
            .state("multi",{
                url: "/multi",
                    "viewA@multi": {
                        templateUrl: "app/templates/login.htm",
                        controller: ["$scope", "getChildrenNumber", function($scope, getChildrenNumber){
                            this.nameApp = "nameAppChanged";
                            this.gatto = "Miao";
                        }],
                        controllerAs: "ctrl"
                    }
                },
                resolve: {
                    getChildrenNumber: ["$http", function($http, httpPost){
                        var httpP = httpPost.get("http://domain.com/user/login/api-login", $.param({ username:"ciaociao6@ciao.com", password:"ciaociA0" }), httpConfig)
                        console.log(httpP);
                        return "Some response from an API";
                    }]
                }
            });
angular
    .module("CiaoMiao")
    .config(config);

As result of console.log I got "undefined", I don't get how to inject that factory at this part of the code. I tried to put into the main controller of that view, but it didn't work as well.

解决方案

(If you place the resolve at your view it should work. If you need that resolve in multiple views of the same state. I would try to use an abstract state and add the resolve there.) Works but is not needed (see edit below.)

Please have a look at this jsfiddle or the demo below.

I've reduced the demo a bit to keep things easier to read. Also not added array notation for DI in the demo. You don't need to use the deferred object in your factory because $http is already returning a promise.

Edit: You can place the resolve outside of the view and it should work too. I've tried it in this fiddle. So there's probably a different issue in your code.

OK, I think the problem with your code is that you're not returning the resolved value from your promise. Something like promise.then(function(response) {return response;});

angular.module('demoApp', ['ui.router'])
    .factory('myDataFactory', function ($http) {
    return {
        get: function (id) {
            return $http.post('http://crossorigin.me/http://www.mocky.io/v2/55a65562b2016ce10c7e6ea9', {
                id: id
            }).then(function (response) {
                return response;
            });
        }
    };
})
    .config(function ($urlRouterProvider, $stateProvider) {
    $urlRouterProvider.otherwise('/124');

    $stateProvider.state('home', {
        url: '/:id',
        views: {
            'viewA': {
                template: '{{hello}}',
                controller: 'homeController',
                resolve: {
                    backendData: function (myDataFactory, $stateParams) {
                        return myDataFactory.get($stateParams.id);
                    }
                }
            },
            '@': {
                template: 'main view'
            }
        }

    });
})
    .controller('homeController', function ($scope, backendData) {
    console.log(backendData);
    $scope.hello = backendData;
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js"></script>
<div ng-app="demoApp">
    <div ui-view=""></div>
    <div ui-view="viewA"></div>
</div>

这篇关于我如何在“解决"中使用工厂?$stateProvider 的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆