我创建了一个基本的 AngularJS 应用程序,它使用 Yelp 的 API,但无法$httpProvider.interceptors
解析我的响应。
这是我的应用程序:
var app = angular.module("restaurantList", []);
我的yelpAPI
服务(未图示)验证我的 API 请求并生成 HTTP 请求。然后我将收到的数据输出到 Web 控制台,如下所示:
app.controller("mainCtrl", ["$scope", "yelpAPI", function ($scope, yelpAPI) {
$scope.restaurants = [];
yelpAPI.get(function (data) {
$scope.restaurant = data;
console.log($scope.restaurant);
});
}]);
这是我请求的数据:
Object {region: Object, total: 37, businesses: Array[20]}
我想要位于businesses
属性中的数组。所以,我认为用它$httpProvider.interceptors
来解析在Object.businesses
数组中找到的对象是个好主意。
这是$httpProvider.interceptors
我提出初始请求时的样子:
app.config(function ($httpProvider) {
$httpProvider.interceptors.push(function () {
return {
response: function (response) {
return response;
}
}
});
});
这是现在的$httpProvider.interceptors
样子:
app.config(function($httpProvider) {
$httpProvider.interceptors.push(function() {
return {
response: function(response) {
var old_response = response.businesses,
new_response = [];
for (var i = 0; i < old_response.length; i++) {
var obj = old_response[i],
new_obj = {
restaurant_name: obj.name,
phone_number: obj.display_phone,
yelp_rating: obj.rating,
reservation_url: obj.reservation_url
};
new_response.push(new_obj);
}
return new_response;
}
}
});
});
现在,我收到一条错误消息,上面写着TypeError: Cannot read property 'businesses' of undefined
. 有什么我忽略的吗?
编辑#1
我console.log(response)
在拦截器内部使用来打印我的响应,发现response.businesses
实际上应该是response.data.businesses
. 这解决了我的错误,但现在我的$http
电话返回了undefined
。知道我的新问题可能是什么吗?
编辑#2
app.factory("yelpAPI", function($http, nounce) {
return {
get: function(callback) {
var method = "GET",
url = "http://api.yelp.com/v2/search";
var params = {
callback: "angular.callbacks._0",
oauth_consumer_key: "my_oauth_consumer_key",
oauth_token: "my_oauth_token",
oauth_signature_method: "HMAC-SHA1",
oauth_timestamp: new Date().getTime(),
oauth_nonce: nounce.generate(),
term: "American",
sort: 2,
limit: 20,
radius_filter: 4000,
deals_filter: true,
actionlinks: true
};
var consumerSecret = "my_consumer_secret",
tokenSecret = "my_token_secret",
signature = oauthSignature.generate(method, url, params, consumerSecret, tokenSecret, {
encodeSignature: false
});
params["oauth_signature"] = signature;
$http.jsonp(url, {
params: params
}).success(callback);
}
}
});