javascript - 在$http.then()中做事,然后返回promise

标签 javascript angularjs promise angular-promise

initUserProfile: function() {

  return $http.get('myapi/user/profil').
  then(function(response) {
    current_user = response.data;
    if (current_user.profilpicture) {
      current_user.profilpicture = $rootScope.baseURL + "/images/users/" + current_user.username + "/" + current_user.profilpicture;
    }
  }, function(err) {
    // log error
  });
};

我希望它返回一个 promise ,这里就是这种情况,但它是 $http 成功 promise 。 当 then() 内的更改完成时,我该如何返回 promise ?

最佳答案

只需在 then() 中返回 current_user,它将可作为链中下一个 then() 的参数

initUserProfile: function() {

  return $http.get('myapi/user/profil').
  then(function(response) {
    current_user = response.data;
    if (current_user.profilpicture) {
      current_user.profilpicture = $rootScope.baseURL + "/images/users/" + current_user.username + "/" + current_user.profilpicture;
    }

     return current_user;


  }).catch(function(err) {
    // log error
  });
};

在 Controller 中:

myService.initUserProfile().then(function(current_user){
    $scope.user = current_user;
})

关于javascript - 在$http.then()中做事,然后返回promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38510378/

相关文章:

javascript - Angular Js 弹出菜单

javascript - function.apply.bind 在以下代码中如何工作?

javascript - “Unhandled stream error in pipe” - 使用带有 express 的 request.js 下载的文件太多

javascript - 为什么我的 promise 在 Angular JS 中不起作用?

javascript - 组织 AngularJS Controller

javascript - 使用 AngularJS 更改动态表的特定 td 行的背景

javascript - Heroku process.env.port 未定义

javascript - Java脚本中的游戏。我应该使用 Canvas 吗?

javascript - 类型错误 : Cannot read property 'book' of undefined at BookDetails. 渲染

javascript - 世博客户端 : Fast Refresh not working (React Native)