如何将promise值传递给函数

时间:2017-08-01 05:22:05

标签: javascript angularjs

我在下面有一段角度代码。

我需要传递一个值,它来自一个承诺,代码中的**value**

以下是我的承诺

Auth.loggedInUser().then(function (user){
  return user.id
}); 

下面是角度代码

.run(['$rootScope', 'ngCart','ngCartItem', 'stores', function ($rootScope, ngCart, ngCartItem, stores) {

    $rootScope.$on('ngShoppingCart:changed', function(){
        ngCart.$save();
    });

    if (angular.isObject(stores.get(**value**))) {
        ngCart.$restore(stores.get(**value**));

    } else {
        ngCart.init();
    }

}])

如何将上面的异步函数中返回的值(值)传递给角度代码中的 value ?不确定正确的方法。

2 个答案:

答案 0 :(得分:2)

也许这会起作用

.run(['$rootScope', 'ngCart','ngCartItem', 'stores', function ($rootScope, ngCart, ngCartItem, stores) {

    $rootScope.$on('ngShoppingCart:changed', function(){
        ngCart.$save();
    });
    Auth.loggedInUser().then(function (user){
        if (angular.isObject(stores.get(user.id))) {
            ngCart.$restore(stores.get(user.id));

        } else {
            ngCart.init();
        }
    }); 

}])

答案 1 :(得分:0)

注入auth服务以运行并使用promise

中的正则表达式
.run(['$rootScope', 'ngCart', 'ngCartItem', 'stores', 'Auth', function($rootScope, ngCart, ngCartItem, stores, Auth) {

    $rootScope.$on('ngShoppingCart:changed', function() {
        ngCart.$save();
    }); 

    Auth.loggedInUser().then(function(user) {

        if (angular.isObject(stores.get(user.id))) {
            ngCart.$restore(stores.get(user.id));

        } else {
            ngCart.init();
        }
    });

}])