【问题标题】:How to return response to function from .then() in angular? [duplicate]如何从 .t​​hen() 角度返回对函数的响应? [复制]
【发布时间】:2018-08-24 02:28:56
【问题描述】:

check()是从html中调用的,返回值应该是true/false。

ng-class="{'timeline-inverted: check(id)'}"

$scope.server.get() 从服务器脚本获取result(r),我需要将$scope.result 返回给check() 函数。

这是我的 Angular 代码:

$scope.check = _.memoize(function(userId) {
    $scope.server.get({
        action: 'checkif',
        userID: userId
    }).then(function successHandler(r) {
        $scope.result = r.data.result;
    });
    return $scope.result;   // $scope.result is undefined
});

【问题讨论】:

  • 你的回报应该在.then你试过了吗?
  • @Fix3r 是的,不工作。

标签: javascript angularjs http get response


【解决方案1】:

创建一个新的 Promise,然后在 HTTP 调用成功后解析。

$scope.check = _.memoize(function(userId) {
  return new Promise((resolve, reject) => {
    $scope.server.get({
      action: 'checkif',
      userID: userId
    }).then(function successHandler(r) {
      resolve(r.data.result);
    });
  });
});

【讨论】:

  • memoize 在这里没有任何意义。它目前正在缓存返回的promise,而不是返回的数据。
  • 我从来没有使用过lodash,我只是给出了返回值的常用方式。
【解决方案2】:

首先,在这里使用memoize 并不是一件好事。 memoized 工作得很好,因为参数具有原始类型。由于您调用 API,您无法确定相同的 userIdaction 参数返回了相同的数据集!

我不知道为什么您的$http 调用绑定到$scope。也许将这些东西放在服务中会更好。最后,您的应用程序可能看起来像这样一个漂亮的结构化应用程序:

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope, user) {

   $scope.userData = null;

   user.get('checkif', 2).then(function (result) {
      $scope.userData = result.data.result;
   });
});


myApp.service('user', function () {
  this.get = function (action, userId) {
    return $http({
      url: 'http://your-api-endpoint/',
      method: 'GET',
      params: {
        action: action,
        userID: userId
      }
    });
  }
});

【讨论】:

  • 我无法在我的应用程序中使用 url..
  • 为什么不能在应用程序中使用 URL 以及如何获得 API 结果?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-14
  • 2019-10-13
  • 2015-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-17
相关资源
最近更新 更多