如果我尝试在“视图”中使用“解决”,为什么angularjs会引发错误?

时间:2015-07-17 11:47:11

标签: angularjs angular-ui-router

正如我所写,也许我不能使用“解决”INSIDE“观看”但只能用于“观看”

我正在试图弄清楚如何避免对同一个API / url进行多次ajax调用,因为如果我按原样使用getChildren,并且我在N subview @ views中使用它,则angular会调用N ajax。

routes.js:

.state("multi",{
            url: "/multi",
            views: {

                "viewB@multi": {
                    templateUrl: "app/templates/login.htm",
                    controller: ["$scope", "httpPost", "getChildrenNumber", function($scope, httpPost, getChildrenNumber){
                        this.children = getChildrenNumber.data.errorMessage + " Miao";

                    }],
                    controllerAs: "ctrl"
                },
                "viewC@multi": {
                    templateUrl: "app/templates/viewC.htm",
                    controller: ["$scope", "getLogin", function($scope, getLogin){
                        this.secondErrorMsg = getLogin.data.errorMessage;
                    }],
                    controllerAs: "ctrl"
                },
                resolve: {
                    getLogin: function(httpPost){
                        return httpPost.get("http://domain.com/user/login/api-login", { username:"ciaociao6@ciao.com", password:"ciaociA0" } );

                    }
                }
            },
            resolve: {
                getChildrenNumber: function(httpPost){
                    return httpPost.get("http://domain.com/user/login/api-login", { username:"ciaociao6@ciao.com", password:"ciaociA0" } );

                }
            }
        });

2 个答案:

答案 0 :(得分:1)

就像你说的那样,你不能使用:

views: {
  someView: {},
  someOtherView: {},
  resolve: {}
}

你可以选择这样的事情;

state: {
  resolve: {
    getChildren: function () {}, // one time.
    getLogin:    function () {} // one time.
  },
  views: {
    /** 
     * Inject the resolved values into 
     * your view controllers. 
     */
    viewA: {
      controller: function (getChildren, getLogin) {}
    },
    viewB: {
      controller: function (getLogin) {}
    },
    viewC: {
      controller: function (getLogin) {}
    }
  }
}

解析功能只运行一次,在视图中共享。

<强> jsfiddle

答案 1 :(得分:0)

在一个promise中包含调用,让所有resolve函数返回相同的promise。

因此,只有第一个调用创建了promise,所有其他调用才会返回promise

这样的事情:

var defer;
function login() {
    if(!defer) {
        defer = $q.defer();
        httpPost.get("http://domain.com/user/login/api-login", 
           { username:"ciaociao6@ciao.com", password:"ciaociA0" })
           .success(function(data) {
               defer.resolve(data);
           }
       );
    }
    return defer.promise;
}


function resolve1() {
    return login();
}


function resolve2() {
    return login();
}


function resolve3() {
    return login();
}

```