Angularjs strongloop custom method - angularjs

I have defined a custom method in my strongloop application, which returns the right datas when I test it through the Api explorer.
I then generated the an angularjs service thanks to "lb-ng".
When I send a request with this custom method through angular I get this error :
Error in resource configuration for action `list`. Expected response to contain an object but got an array (Request: GET http://**myip**/api/Questions)
The thing is it should call this address instead :
http://**myip**/api/Questions/4/0
It used to work at some point, before a regenerated an angular service with lb-ng
Here is the method registration in strongloop :
Question.remoteMethod(
'list', {
http: {path: '/:lang/:start/', verb: 'get'},
accepts: [
{arg: 'lang', type: 'number'},
{arg: 'start', type: 'number'}
],
returns: {arg: 'questions', type: 'array'},
description: ['Returns an array obj the latest added questions filters by language and categories']
}
)
And here is the calling test in angular in my homeController :
function getQuestions(langId, start) {
Question.list(langId, start)
.$promise
.then(function(questionsList) {
$scope.questions = questionsList.questions;
}
);
}
getQuestions(4, 0);
Do you have any idea why the method is not calling the address with arguments ?

I am pretty sure that request parameters need to be on an object (as per the REST API use via explorer) as follows:
Question.list({lang:langId, start: start}).$promise.then(...)
I would also suggest generating the docular docs for the angular SDK as these help clarify things.

In the service file that was generated look for the list method and add/set the isArray parameter as true, it should be something like this:
"list": {
...
isArray: true,
...
}

Related

How can i create a loopback remote method for search

In my loopback application i have a model named test. I need to search details and display the details based on multiple criteria. that is the search fields are status, priority, message and id. i want to dispalt the details based on these search fields. suppose i give status is open and priority is low the details should be satisfied with both these condition(that is "AND" operator).How should i implement this? My db is Arango Db. what i have is common/models/test.js
test.js
module.exports = function (Test) {
Test.search = function(callback){
}
};
How should i implement this? I am new to loopback and angular. Any help will really helpfull.
Implementing a remote method is documented here.
It requires two things. First, create the function that will be called remotely. Here, you've called it search.
Function parameters should include all request arguments (status priority message id) and a callback as last argument.
Then, register this function as a remote method.
In your case, it should give the following code
module.exports = function(Test){
Test.search = function(status, priority, message, id, cb) {
var results = ...// Your custom logic to find the results
if (err) return cb(err); // if something went wrong. err is returned by your custom logic
cb(null, results); // if results were found
}
Test.remoteMethod('search', {
http: {
verb: 'get'
},
accepts: [
{arg: 'status', type: 'string', http: { source: 'query' } },
{arg: 'priority', type: 'string', http: { source: 'query' } },
{arg: 'message', type: 'string', http: { source: 'query' } },
{arg: 'id', type: 'number'},
],
returns: {arg: 'results', type: 'Object'} // To return a JSON object for instance
});
};
Then, call your method with GET api/Tests/search?status=open&priority=high&...
For searching entries, you might also use the querying approach

AngularJs $resource, REST and Symfony2 FOSRestBundle

I am using the FOSRestBundle, this bundle generates routes for me and pluralises those routes. For instance a GET request to /users.json is different from a GET request to /user/15.json
Its worth noting that a call to /users/15.json fails.
More on this issue here https://github.com/FriendsOfSymfony/FOSRestBundle/issues/247
In my Angular app I use a $resource to create a RESTful call, the URL is a template as detailed here https://docs.angularjs.org/api/ngResource/service/$resource
For example
$resource('http://example.com/:id.json')
Or
$resource('http://example.com/user/:id.json')
And there in is the problem, the $resource seems to accept a single URL template for the REST resource, but I have multiple ones because of the forced pluralisation from the FOSRestBundle.
I do not think hacking the FOSRestBundle is the answer, so what can I do with my usage of $resource in AngularJs to correct this issue?
you can set url for every method as third parameter - actions
angular.module("example", ["ngResource"])
.factory("userService", function($resource) {
return $resource("http://example.com/user/:id.json", {
id: "#id"
}, {
'query': {
url: "http://example.com/users"
}
})
})
.run(function(userService) {
userService.query();
userService.get({id:1});
})

Using locale in the $resource URL

My AngularJS application is getting server data from a rails JSON API and the API routes are localized, for example:
/:locale/api/categories/
I am trying to define a $resource that would enable the localization. So far, I've been unsuccessful (see the approaches I've tried below).
First attempt
$resource('/:localeId/api/categories/:categoryId', {
localeId: $locale.id,
categoryId: "#id",
format: 'json'
})
This does not work. The localeId is only evaluated once, when the $resource is created.
Second attempt
$resource('/:localeId/api/categories/:categoryId', {
localeId: "$locale.id",
categoryId: "#id",
format: 'json'
})
This does not work either, the generated URL is /$locale.id/api/categories/.
Third attempt
$resource('/:localeId/api/categories/:categoryId', {
localeId: "#localeId",
categoryId: "#id",
format: 'json'
})
This works but obliges me to define localeId everytime I use my $resource.
Is there a better way to automatically use $locale.id inside my $resource URL?
Just provide a function that returns your value (see documentation):
$resource('/:localeId/...', {
localeId: function () {
return $locale.id;
},
// ...
})

extjs using jsonp,Accessing data from remote url

with extjs,i m runnig the server from one system,giving the url in another system and i m using JSONP in extjs ver:4.02,when i check in response i m getting data in json format,when i try to print in console or Store im not getting..here is my extjs code...
<script type="text/javascript">
Ext.Ajax.cors = true;
Ext.Ajax.useDefaultXhrHeader = false;
Ext.define('User', {
extend: 'Ext.data.Model',
fields: ['empid', 'name', 'email']
});
var myStore = Ext.create('Ext.data.Store', {
model: 'User',
autoLoad:true,
proxy: {
type: 'jsonp',
// url : 'data/tagfamily.json',
url:'http://192.168.7.70:8080/palamanagement/user/getAllRecords',
},
listeners:{
'load':function( store, records, successful, eOpts ){
alert(records);
console.log(records);
}
}
});
You literally have to return something like the following:
someCallback({
users: [
{
id: 1,
name: "Ed Spencer",
email: "ed#sencha.com"
}
]
});
So you already have the JSON the way you need it; you just need your server response to wrap the JSON in the callback so that the JSONP proxy can execute and load your store with data.
Therefore, when handling the JSONP request, your server's script needs to recognize the "callback" param that is sent as a part of the request. It then needs to use the value of this param to wrap your JSON response.
Be sure to read the docs that both myself and Oguz have posted: they outline the requirement pretty well. But if you don't respond with a callback, you'll never get your standard JSON response to work with the JSONP proxy.
When you request from DOMAIN-A to DOMAIN-B, you should provide a call back function in proxy definition. The callback function will use in after request complete.
For instance, in Flickr REST service, there is jsoncallback parameter which we should give our function name in order to complete our request. In this way, our request url will be:
.../?jsoncallback=ourFunction
To be able to provide our function name, there is a property in ExtJS which is callbackKey.
Like so:
Ext.define('User', {
extend: 'Ext.data.Model',
fields: ['empid', 'name', 'email']
});
Ext.data.JsonP.request('http://api.flickr.com/services/feeds/photos_public.gne', {
callbackKey: 'jsoncallback',
callback: ourFunctionName
});
or
Ext.data.JsonP.request('http://api.flickr.com/services/feeds/photos_public.gne', {
callbackKey: 'jsoncallback',
callback: function(data) {
...
}
});
PS: I know, you will not find callback property in doc but just to be sure there is. Check ext-all-debug-w-comments.js file, line 108486
Flickr Callback Function
JsonP callbackKey

Web2py and Sencha

I'm new to Web2py and Sencha, and I would like to see a simple example using both frameworks. I have googled but I haven't found anything.
Many thanks for your help.
Finally I got everything working. To ensure that the js files are rendered it is necessary to paste them in the static folder of the web2py project. With Sencha Architect I have created a project in the mentioned location, so for example to call the controller from the js view an Ext.Ajax.request is made:
onDataRender: function(component, eOpts) {
Ext.Ajax.request
({
url: '/r/rec/getdata',
method: 'GET',
params: '',
success: function(response)
{
o=Ext.decode(response.responseText);
component.setSource(o);
console.log(response.responseText);
},
failure: function(response)
{
component.setSource({"Error" : "No data"});
console.log(response.responseText);
}
});
},
The controller then gets the resquested data from database, generates a json and returns it to the view layer:
def getdata():
jsondata="{"
data=db.song.find()
for s in data:
jsondata+="\""+str(s["_id"])+"\" : \""+str(s["name"]).replace("\"","")+"\","
return jsondata[:-1]+"}"
The getdata method gets all the data (it is a test example), to get a specific record the id can be passed as a parameter with request.args(0).

Resources