I am currently developing an angular application and I have a controller that interacts with a service. The controller sends a URL to the service, which then makes a GET request to that URL and receives JSON data in return. Within this JSON data is a URI for HTTP requests. I extract this URI from the JSON and proceed to redirect the browser to it.
The JSON returned from the endpoint is structured as follows:
{
"profile":"...",
"releases_url":"http://...",
"name":"...",
...,
"uri":"http://the-value-i-want-to-return.com",
...,
}
Service Code snippet:
// Resolves an API endpoint link to its Http counterpart
function resolveJSONEndpointToHttpUrl(JSONEndpointUrl) {
return $http({ method: 'GET', url: JSONEndpointUrl }).
success(function (data, status, headers, config) {
console.log("resolveJSONEndpointToHttpUrl : data");
console.log(data);
//return data;
}).
error(function (data, status, headers, config) {});
}
Controller Code snippet:
function redirectViaJSONLink(url) {
return musicCollectionService.resolveJSONEndpointToHttpUrl(url).then(function (data) {
console.log("redirectViaJSONLink : data");
console.log(data);
console.log("redirectViaJSONLink : data.data");
console.log(data.data);
console.log("redirectViaJSONLink : data.data.uri");
console.log(data.data.uri);
// Perform redirection
// $window.location.href = data.uri;
});
}
In order to understand the JSON response more clearly, I am logging each step of the process to analyze what is being returned and how to access its properties effectively.
My inquiries are:
- Why is there no need to include
return data;
in the$http .success
callback? When would a situation arise where this is necessary? - Is there a way to directly return a specific property from the data object within the
$http .success
callback so that I do not have to repeatedly calldata.data.uri
in my controller function? Alternatively, can the structure of the JSON payload be modified before it reaches the controller?