Having some trouble parsing the response of my basic AngularJS app that consumes Yelp's API using $httpProvider.interceptors
.
This is the structure of my app:
var app = angular.module("restaurantList", []);
The yelpAPI
service handles authentication and generates an HTTP request. The received data is output to the Web Console as follows:
app.controller("mainCtrl", ["$scope", "yelpAPI", function ($scope, yelpAPI) {
$scope.restaurants = [];
yelpAPI.get(function (data) {
$scope.restaurant = data;
console.log($scope.restaurant);
});
}]);
The data from the request looks like this:
Object {region: Object, total: 37, businesses: Array[20]}
I aim to parse the array nested in the businesses
property. My approach was to utilize $httpProvider.interceptors
for this purpose.
The initial configuration of $httpProvider.interceptors
:
app.config(function ($httpProvider) {
$httpProvider.interceptors.push(function () {
return {
response: function (response) {
return response;
}
}
});
});
The updated version of $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;
}
}
});
});
An error is now showing up -
TypeError: Cannot read property 'businesses' of undefined
. Any suggestions on what I might be missing?
EDIT #1
After printing the response using console.log(response)
, I realized that response.businesses
should actually be response.data.businesses
. This fixed the error, but now my $http
call is returning undefined
. Do you have any insights on what could be causing this issue?
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);
}
}
});