zl程序教程

您现在的位置是:首页 >  其它

当前栏目

[AngularJS] Promises in config. 2. config().when()

in angularjs config when promises
2023-09-14 08:59:21 时间

Before we see how promise works in contrller. But in contrller it is not a good way to put promises.

When you route the page, before the controller get excuted and templated loaded, you can use 'resolve' keyword in config or service or factory.

Here we show how to use promise in config.

'resolve' get loaded before controller and template, good to load $http stuff.

            resolve: {
//appXXX is the ng-app appXXX:
function($q, $timeout){ //inject two services, function can inject services!!! var defer = $q.defer(); $timeout(function(){defer.resolve()}, 2000); return defer.promise // it is important to return the defer.promises .then(console.log("logout 1")) .then(console.log("logout 2")); } },

 

var app = angular.module("app", ["ngRoute"]);
app.config(function($routeProvider) {
    $routeProvider
        .when('/',
        {
            resolve: {
                doFirst: function($q, $timeout){
                    var defer = $q.defer();
                    $timeout(function(){defer.resolve()}, 2000);
                    return defer.promise
                        .then(console.log("logout 1"))
                            .then(console.log("logout 2"));
                }
            },
            templateUrl: "app.html",
            controller: "AppCtrl"
        })
});
app.controller('AppCtrl',function($scope){
    $scope.model = {message: "It is great!"}
});