javascript - Angular - 如何将参数传递到延迟 promise 中?

标签 javascript angularjs

在这里开发我的第一个 Angular 应用程序,如果问题不清楚,请原谅。

我有一项服务 gets从我的 api 使用 header 中的组变量。

var theReq = {
   method: 'GET',
   url: API + '/homeq',
   headers: {
     'group': 'mobile'
   }
};

$http(theReq)
.then(function(data){
    deferred.resolve(data);
})

self.getResults = function() {
    return deferred.promise;
}

我面临的问题是使用 group我指定的变量而不是预设的变量。

我当然可以将它传递到该函数(即 self.getResults = function(groupToGet) ),但它如何从那里到达 theReq我处理的?

感谢任何帮助。

谢谢。

最佳答案

您需要按以下方式修改您的函数。 $q 是创建延迟对象的服务。您需要注入(inject)它。

self.getResults = function(groupToSet) {

  var deferred = $q.defer();
  var theReq = {
    method: 'GET',
    url: API + '/homeq',
    headers: {
       'group': groupToSet
    }
  };

  $http(theReq)
  .then(function(data){
     deferred.resolve(data);
  })


  return deferred.promise;
}

你可以使用 Promise 作为

self.getResults("mobile").then(function(data) {
  //success function here.
}).catch(function(error) {
  //error function here
});

关于javascript - Angular - 如何将参数传递到延迟 promise 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35625319/

相关文章:

javascript - 我的 javascript 阻止我的代码工作

javascript - 获取 RangeError : using angular. js 和 php

javascript - 命名 ng-app 会破坏 angularjs 中的数据绑定(bind)

angularjs - Node.js 未满足对等依赖关系的 Angular 核心和 Angular http

javascript - 如何以 Angular 方式从 JSON 访问所有数组值

Javascript/JSON : Object of object converted to associative array

javascript - 在 bootstrap-vue 选择选项中插入图像

javascript - FlowJS 类型以及使用 && 和赋值

javascript - 无法使用 jQuery animate() 使元素对 Angular 移动

javascript - 检查对象中是否存在某个元素