Я создал базовое приложение AngularJS, которое использует API Yelp, и у меня возникли проблемы с использованием $httpProvider.interceptors
для анализа моего ответа.
Вот мое приложение:
var app = angular.module("restaurantList", []);
Моей yelpAPI
служба (не на фото) проверяет подлинность моего запроса API и генерирует запрос HTTP. Я тогда выводить данные, полученные с веб-консоли, как так:
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
. Есть ли что-то, что я пропускаю?
EDIT # 1
Я использовал console.log(response)
внутри перехватчика, чтобы напечатать мой ответ и обнаружил, что response.businesses
должно быть на самом деле response.data.businesses
. Который разрешает мою ошибку, но теперь мой вызов $http
возвращает undefined
. Любая идея, какова моя новая проблема?
EDIT # 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);
}
}
});
Просто попробовал это, но не имел успеха. – Wilhelm
Произошла ошибка? –
Да, такая же ошибка. – Wilhelm