In my service, i want to load the path through another service - java

I have an angular webapp.
It has one service that will query a simple node api on the same server.
That api takes the name of an environment variable as parameter and return the path to the java api that matches that environment variable.
servicesModule.factory('EnvVarApi', function($http){
var url = 'http://localhost:8080/api/variable_env/';
return {
getUrlApi : function(var_env, callbackSuccess) {
$http.get(url+ var_env).success(callbackSuccess);
}
}
});
This works fine. It returns an object of the form:
{"cle" : API_KEY, "valeur" : API_PATH}
Now i want to create another service, that will query that java api (I will have 3 of them at the end)..
How would i go about retrieving the path to that API only ONCE? And once it loaded return the correct resource. Atm it's breaking because the resource returned has a null path before the callback.
servicesModule.factory('ApiRef', function($resource, EnvVarApi){
var url = null;
EnvVarApi.getUrlApi('APIREF_KEY', function(data) {
if (data) {
url = data.valeur;
}
});
return $resource(url, {'cle' : '#cle'}, {
put : {method : 'PUT'}
});
});
The first call is made fine and return the path, however as expected it breaks because i'm return a $resource with a null url at first.
And there is maybe a better way to do that than to inject my first service in my second service.
EDIT : FIXED thanks to answer marked bellow.
Here the final code:
servicesModule.factory('EnvVarApi', function($http){
var url = 'http://localhost:8080/api/variable_env/';
return {
getUrlApi : function(var_env) {
return $http.get(url+ var_env);
}
}
});
And
servicesModule.factory('ApiRef',['$q','$http', 'EnvVarApi',function ($q,$http, EnvVarApi) {
var defer = $q.defer();
EnvVarApi.getUrlApi('APIREF_KEY').then(function (resp) {
defer.resolve($http.get(resp.data.valeur));
});
return defer.promise;
}]);

You can use $q service, check code below
app.factory('call2',['$q','$http',function ($q,$http) {
var url = 'whatever url';
var defer = $q.defer();
$http.get(url).then(function (resp) {
defer.resolve($http.get(resp.data));
//resp.data contains the returned by $http request URL object
});
return defer.promise;
}]);
At Controller o Directive side (remember to inject service into controller)
call2.then(function (resp) {
$scope.response = resp.data;
//resp.data will contain the response of '$http.get(resp.data)'
})
you can use $resource instead of $http.get, see below
app.factory('call2', ['$q', '$resource', function ($q, $resource) {
var url = 'whatever url';
var defer = $q.defer();
$resource(url).get(function (resp) {
defer.resolve($resource(resp.url).get().$promise);
});
return defer.promise;
}]);

$http.get returns a promise, the simple thing to do is to resolve the promise in your controller... not in a factory. Meaning no .success() in your factory... only in the controller
If you need this in the service... it would be like so:
servicesModule.factory('ApiRef', function($resource, EnvVarApi){
var url = null;
// this is ASYNC, meaning it will got to the return statement below and wait until the promise is resolved to assign the url
EnvVarApi.getUrlApi('APIREF_KEY', function(data) {
if (data) {
url = data.valeur;
$resource(url, {'cle' : '#cle'}, { // url defined here, gets put correctly
put : {method : 'PUT'}
});
}
});
return $resource(url, {'cle' : '#cle'}, {
put : {method : 'PUT'}
});
});

Related

How to pass an input value from a modal-dialog in HTML and get it in java servlet using AngularJS? [duplicate]

Does anyone know why this does not work?
$http
.get('accept.php', {
source: link,
category_id: category
})
.success(function (data, status) {
$scope.info_show = data
});
and this does work:
$http
.get('accept.php?source=' + link + '&category_id=' + category)
.success(function (data, status) {
$scope.info_show = data
});
The 2nd parameter in the get call is a config object. You want something like this:
$http
.get('accept.php', {
params: {
source: link,
category_id: category
}
})
.success(function (data,status) {
$scope.info_show = data
});
See the Arguments section of http://docs.angularjs.org/api/ng.$http for more detail
From $http.get docs, the second parameter is a configuration object:
get(url, [config]);
Shortcut method to perform GET request.
You may change your code to:
$http.get('accept.php', {
params: {
source: link,
category_id: category
}
});
Or:
$http({
url: 'accept.php',
method: 'GET',
params: {
source: link,
category_id: category
}
});
As a side note, since Angular 1.6: .success should not be used anymore, use .then instead:
$http.get('/url', config).then(successCallback, errorCallback);

Is there anyway to get a Rest service call to return a plain String?

I am writing a Rest service that checks to see if any providers are ingesting. If so return true and if not return false. I wouldn't mind if it returned a boolean but I couldn't find anything about it when doing research. This is the javascript that calls the rest service in a ajax call:
var result = $.ajax({url:cdpeConfig.providerUrl+'/updateStatus',type: 'GET'});
if (result=="true"){
alert(result);
}
else{
alert(JSON.stringify(result));
}
the json.stringify is the only way I have been able to see what it returns. All I have seen it return is {"readyState":1}
Here is the java:
`#GET
#Path("/updateStatus")
#Produces({MediaType.TEXT_PLAIN})
public String isIngesting(){
String result = "false";
List<Provider> providers = new ArrayList<Provider>();
providers = providerManager.getAllProviders();
for (Provider provider : providers) {
if (provider.getUpdateStatus().toLowerCase().equals(CdpeEnum.UpdateStatus.INGEST.toString().toLowerCase()) ) {
result = "true";
}
}
return result;
}`
var result = $.ajax({url:cdpeConfig.providerUrl+'/updateStatus',type: 'GET'});
result.done(function(data){
alert(data);
});
done method is the success function in jquery ajax. It will execute once your request is completed.

AngularJS DELETE request to my REST webservice is in plain text?

So I am trying to wire up an AngularJS front-end to a Java Spring back-end using a REST service.
My DELETE requests keep getting the following error (notice the speaker?id=) - Why is it generating speaker?id= instead of speaker/ ?
DELETE http://localhost:8082/rest/speaker?id=54200b6b772f1e7b0688307b 405 (Method Not Allowed)
The code is as follows:
Java:
#RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
public void delete(#PathVariable String id) {
speakerService.delete(id);
}
Angular JS service
this.delete = function (id, callback) {
SpeakerResource.delete({ id: id }, function () {
callback();
});
}
Angular JS factory
app.factory('SpeakerResource', function ($resource) {
return $resource('rest/speaker/:speakerId',
{
speakerId: '#speakerId'
},
{
'update': { method: 'PUT' }
},
{
'delete': { method: 'DELETE', params: {id: '#speakerId' } }
}
If I use the $http statement then everything works correctly, but obviously I'd like to stick to using the factory as the PUT/POST methods are working fine!
$http.delete('http://localhost:8080/rest/speaker/' + data.id);
Cheers,
I think you should remove the params object on the delete action or rename the parameter to speakerId, because otherwise AngularJS cant set the url parameter in the resource (your url placeholder is speakerId, but your property is named id)

porting jquery to java

i have a jquery cod with me and i want to port it to java. Is there any options available to do this task quickly since i am not familiar with java
Here is my code
ASDR.PostStore = function(ec, options) {
this.ec = ec;
this.target = options && options.target;
var self = this;
var _send = function(url, transaction, pre, post) {
$(transaction).trigger(pre);
$(self).trigger(pre, transaction);
$(self).trigger('sending', transaction);
$.ajax({
type : "POST",
url : url,
data : transaction.toString(),
dataType: "json",
success : function(data) {
ec.expand(data, true);//Always updateOnIntern
$(self).trigger('sent', data);
$(self).trigger(post, data);
$(transaction).trigger(post, data);
},
error : function(data){
console.log("Logging error", data);
}
});
};
this.get = function(transaction) {
var url = (this.target + "get");
_send(url, transaction, 'getting', 'gotten');
}
this.persist = function(transaction) {
var url = (this.target + "persist");
_send(url, transaction, 'persisting', 'persisted');
}
/**
* Always asynchronous.
*/
this.is_async = function(){
return true;
}
}
}
Thanks in advance
Renjith Raj
jQuery is Javascript, which is usually executed on the client side. Java is a program language which is executed on the server side. You cannot directly convert jQuery to Java.
You can however use a library such as GWT which translates Java to Javascript. There is also the possibility to statically render content server side. If you search for JSP/JSTL you'll find many resources.

Solr Jquery AutoComplete Url Source

After browsing thru SO, i found this piece of code everywhere, even I want to implement AutoComplete, I am using Solr to implement search, and wanted to use TermsComponent foe implementing Autocomplet
var cache = {};
$("#textbox").autocomplete({
source: function(request, response) {
if (request.term in cache) {
response($.map(cache[request.term].d, function(item) {
return { value: item.value, id: item.id }
}))
return;
}
$.ajax({
url: "/Services/AutoCompleteService.asmx/GetEmployees", /* I use a web service */
data: "{ 'term': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
cache[request.term] = data;
response($.map(data.d, function(item) {
return {
value: item.value,
id: item.id
}
}))
},
error: HandleAjaxError // custom method
});
},
minLength: 3,
select: function(event, ui) {
if (ui.item) {
formatAutoComplete(ui.item); // custom method
}
}
});
Now my question is, How to configure the url source, wat it should be, the following url
http://localhost:8983/solr/terms?terms.fl=name&terms.prefix=at&wt=json&omitHeader=true
gives me perfect result, now pls tell me wat should be my url source, and if i want to customize add more parameters like terms.lower=py&terms.lower.incl=false&indent=true&wt=json etc ,should i better harcode them in url or in my java class like
List terms = query(q, Integer.parseInt(limit));
private List<TermsResponse.Term> query(String q, int limit) {
List<TermsResponse.Term> items = null;
SolrQuery query = new SolrQuery();
query.addTermsField("spell");
query.setTerms(true);
query.setTermsLimit(limit);
query.setTermsLower(q);
query.setTermsPrefix(q);
query.setQueryType("/terms");
try {
QueryResponse qr = server.query(query);
TermsResponse resp = qr.getTermsResponse();
items = resp.getTerms("name");
} catch (SolrServerException e) {
items = null;
}
return items;
}
Please help, um not so good in jquery, so wanted to confirm one more thing,for wat i need, i just need to modify the url over here or have to customize few more things
It's not very likely that you need to parameterize this client-side, so set those parameters server-side. Setting them with code instead of hardcoding them in the URL is generally better, it reveals the intention. Also remember that you can set parameters in the solr config.
Lastly, don't program by coincidence. Understand the jQuery snippet you're using, otherwise you will have problems sooner or later.

Categories

Resources