2016-09-22 75 views
0

我有一个视图,调用下面这个函数使得我们的API的AJAX调用 - 由于某种原因,当我在AngularScope中使用AngularScope时,总是返回'undefined' Firefox DOM检测工具。如何从AJAX调用(AngularJS)正确地返回我的数据

如果我检查网络标签,我可以看到这个URL已被调用,并可以看到我期待的JSON,然后我想返回data.words JSON数据,但是这总是返回undefined?如果我删除了AJAX调用,并且在最后一次返回时使用了“静态”和“单词”,这在我看来很有效,所以我很清楚AJAX成功调用的返回似乎并不正确... 有任何想法吗??

//内的AngularJS服务文件

this.getAccSignoffWords = function() { 
    var url = ApiService.getDomain() + 'account/signoff'; 
    $http({ 
     method : 'GET', 
     url : url 
    }).success(function(data) { 
     if (data.success) { 
      return data.words; // I want to return this JSON to the scope 
     } 
    }).error(function(data) { 
     throw "Failed to get sign-off words"; 
    })['finally'](function(data) { 

    }); 

    // return [ 'static', 'words' ]; // this line is commented out and only used for testing and is an example of the type of data expected from data.words 
} 
+0

这个函数尝试解析在成功调用数据传回:'数据= JSON.parse(数据)' –

+0

嗨Nishanth,其中这应该放在 - 我要删除成功块内的当前返回 – Zabs

+0

嗯仍然没有喜悦使用,在成功块.. :( – Zabs

回答

1

事情是当你发送http请求,它需要一些时间来处理和发送数据回你的JavaScript代码。但由于JavaScript是异步的,它不会等到响应返回。所以要么你可以返回整个http请求,如Umakanta Behera建议,或者你可以使用回调函数等待单元的响应回来。

this.getAccSignoffWords = function(callback) { 
    var url = ApiService.getDomain() + 'account/signoff'; 
    $http({ 
     method : 'GET', 
     url : url 
    }).success(function(data) { 
     if (data.success) { 
      callback() data.words 
     } 
    }).error(function(data) { 
     throw "Failed to get sign-off words"; 
    })['finally'](function(data) { 

    }); 
} 

呼叫这样

this.getAccSignoffWords(function(data){ 
    console.log(data) // your http response 
}) 
+0

你可以指出第二个'调用'函数与我的代码相关的地方(是这个控制器,服务,视图等)。谢谢 – Zabs

+1

从你的控制器调用它 –

1

,如果你想将其分配到的范围,你应该做的那是因为你的AJAX不返回任何东西..:

var self = this; 
var url = ApiService.getDomain() + 'account/signoff'; 
    $http({ 
     method : 'GET', 
     url : url 
    }).success(function(data) { 
     if (data.success) { 
      self.getAccSignoffWords = data.words; // I want to return this JSON to the scope 
     } 
    }).error(function(data) { 
     throw "Failed to get sign-off words"; 
    })['finally'](function(data) { 

    }); 
0

我认为你没有重新调整$ http结果。请你尝试下面的代码。

this.getAccSignoffWords = function() { 
    var url = ApiService.getDomain() + 'account/signoff'; 
    return $http({ 
     method : 'GET', 
     url : url 
    }).success(function(data) { 
     if (data.success) { 
      return data.words; // I want to return this JSON to the scope 
     } 
    }).error(function(data) { 
     throw "Failed to get sign-off words"; 
    })['finally'](function(data) { 

    }); 

    // return [ 'static', 'words' ]; // this line is commented out and only used for testing and is an example of the type of data expected from data.words 
} 
+0

感谢乌玛卡坦,虽然这给了我同样的问题,虽然 – Zabs

+0

它是否适用于你? –

+0

似乎并不为我工作我正在做一些傻事我很确定,我会继续:) – Zabs

相关问题