AngularJS http返回值 [英] AngularJS http return value

查看:249
本文介绍了AngularJS http返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在AngularJS中编写一个返回值的函数(实际上它是一个字符串)。该值由http请求返回,但异步让我发疯。

I want to write a function in AngularJS that returns a value (actually it is a string). That value is returned by a http request, but async is driving me crazy.

我的第一次尝试是:

this.readParameter = function(key) {
  $http({
    method: "GET",
    url: "XXXXXXX",
    headers: { 'Content-Type': 'application/json' }
  }).then(function successCallback(response) {
    return response.data;
  }, function errorCallback(response) {
    throw new Error("Error");
  })
};

但是由于Angular异步功能(response.data未定义),它当然不起作用

But of course it does not work because of Angular async features (response.data is undefined)

这样做的方法是什么?我只想返回值(字符串),所以我可以使用这个函数,如

What is the way to do it? I just want to return the value (string), so I can use this function like

var a = readParameter("key1")


推荐答案

你可以做的是用初始化定义一些变量函数外部的值和成功函数内的响应设置值而不是返回它。

What you can do is define some variable with initial value outside function and on response set value inside success function instead of returning it.

Delegator 模式在这里工作很好,可以将 $ http 任务分配给某个服务,并使用回调方法进行响应。

Delegator pattern works great here to assign $http task to some service and use callback method for response.

控制器(针对特定请求的呼叫服务) - > 服务(管理请求参数和其他东西并返回工厂对Controller的响应) - > 工厂(发送请求并将其返回服务)

Controller (Call Service for specific request) -> Service (Manage request params and other things and return factory response to Controller) -> Factory (Send request and return it to Service)

回调的基本示例

var myVariable = '';
function myFunction (key, callback) {
  $http({
    method: "GET",
    url: "XXXXXXX",
    headers: { 'Content-Type': 'application/json' }
  }).then(function successCallback(response) {
      callback(response);
  }, function errorCallback(response) {
    throw new Error("Error");
  })
};

function myCallbackFunction(response) {
   myVariable = response.data; // assign value to variable
   // Do some work after getting response
}

myFunction('MY_KEY', myCallbackFunction);

这是设置值的基本示例,而是使用上面示例中的回调模式。

This is basic example to set value but instead use callback pattern from above example.

var myvariable = '';
function myFunction (key) {
  $http({
    method: "GET",
    url: "XXXXXXX",
    headers: { 'Content-Type': 'application/json' }
  }).then(function successCallback(response) {
      myvariable = response.data; // set data to myvariable
      // Do something else on success response
  }, function errorCallback(response) {
    throw new Error("Error");
  })
};
myFunction('MY_KEY');

这篇关于AngularJS http返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆