The function below is being called with no problem. the $save method is being called and my object is being added to mongodb. However, the problem lies in the $location.path() method. For some reason, the $routeParams.quizId is not being taken in account in the URL.
I can see in Chrome that the url it tries to reach is:
GET http://localhost:3000/api/quizes/questions/54a09a248ff7bf9816f272b9 404 (Not Found)
The quizId is missing, the URL should look like this:
http://localhost:3000/api/quizes/quizIdRightHere1234/questions/54a09a248ff7bf9816f272b9
$scope.create = function() {
var question = new Questions({
value: this.value,
type: this.type,
answer: this.answer
});
question.$save({quizId: $routeParams.quizId}, function(response) {
var quizId = $routeParams.quizId;
var url = '/quizes/' + quizId + '/questions/' + response._id;
$location.path(url);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
RouteParams should happen after the hash sign... otherwise it's just different folders.
Related
I have this code in Backbone.js where I am trying to create dynamically a URL and call a function from the controller which returns a JSON data.
For some reason when doing the fetch() method at the end the URL in my browser does not change.
I have put a console.log in my getdata() function just to see if the call is happening, and it does. Also i have tried to console.log the new build URL with the parameter at the end, and also this is build successfully.
Any ideas why the URL in not changing in the browser?
Thank you
getUrl: function(celebname){
var urlstr = "http://localhost/Codeigniter/index.php/testcontroller/getdatabasedata?searchvalue="+celebname;
return urlstr;
},
events: {
"click #submitbtn" : "getdata",
},
getdata: function (event) {
var celebname = $('#celebname').val();
this.model.url = this.getUrl(celebname);
this.model.fetch();
},
Backbone will always try to use the collection url, so if you want to fetch or save you should explicitly save the model with a new url.
Try overriding the url in the model like so:
var newUrl = this.getUrl(celebname);
this.model.save({}, { url: newUrl});
Instead of just setting this.model.url = this.getUrl(celebname);
I am trying to use POST with $resource object in my app.
I have something like this.
Factory:
angular.module('toyApp').factory('toys', ['$resource', function ($resource) {
return $resource('/api/v1/toy/:id/condition/:condid',
{ id: '#id',
condid: '#condid' }
);
}]);
Controller:
$scope.addNew = function() {
//how do I pass id and condid below?
toys.save({'name': 'my first toy'});
})
The above code will pass url like
/api/v1/toy/condition/
I need to send the request url like
/api/v1/toy/6666/condition/abd with parame {'name': 'my first toy'}
How do I do it?
Thanks for the help!
It's very clearly described in the API reference:
https://docs.angularjs.org/api/ngResource/service/$resource
What $resource(url) returns is a class object. If you want to create a new instance and save it, you'll call the $save method on the instance:
var Toy = $resource('/api/v1/toy/:id/condition/:condid',
{id: '#id', condid: '#condid'});
var toy = new Toy({'id': 123, 'condid': 456, 'name': 'my first toy'});
toy.$save();
But if you want to call an object creation API, you'll have to add a custom method to your resource:
var Toy = $resource('/api/v1/toy/:id/condition/:condid',
{id: '#id', condid: '#condid'},
{createToy: {method: 'POST', url: '/create-toy'}});
Toy.createToy({name: 'Slingshot'});
var newToy = new Toys({id: '6666', condid: 'abd'});
newToy.name = 'my first toy';
newToy.$save();
Try this
$scope.addNew = function() {
toys.save({'id': 'foo', 'condid': 'bar'});
})
You are correct in extrapolating $http controller logic to a service/factory.
Create a method to set the object that you will send with the HTTP POST request. Another method to set the url may also be created. The controller will then call these methods before saving to set the url and object to be used for the HTTP call. A dynamic url may be specified in the controller (with unique id and other fields as necessary) and sent to the service.
Service code:
var dataObj = [];
var myUrl = "";
//called from controller to pass an object for POST
function setDataObj(_dataObj) {
return dataObj = _dataObj;
};
function setUrl(_url) {
return myUrl = _url;
}
function saveToy() {
//if sending a different type of obj, like string,
//add "headers: { 'Content-Type': <type> }" to http(method, url, header)
$http({ method: 'POST', url: myUrl })
.then(function(data) {
return data;
})
.catch(function(error) {
$log.error("http.post for saveToy() failed!"); //if log is added to service
});
};
Controller code:
$scope.id = 574; //or set somewhere else
$scope.condid = 'abd';
$scope.objectYouWantToSend = [{"toyName": "Teddy"}];
// to obtain dynamic url for /api/v1/toy/:id/condition/:condid
$scope.url = '/api/v1/toy/' + $scope.id + '/condition/' + $scope.condid;
$scope.addNewToy = function() {
toyService.setUrl(url); //set the url
toysService.setDataObj($scope.objectYouWantToSend); //set the dataObj
toysService.saveToy(); //call the post method;
};
John Papa's AngularJS style guide is well put together and covers scenarios in multiple formats. Below is a link to the data-service factory section:
https://github.com/johnpapa/angular-styleguide#separate-data-calls
I can't see what the problem with this is.
I'm trying to fetch data on a different server, the url within the collection is correct but returns a 404 error. When trying to fetch the data the error function is triggered and no data is returned. The php script that returns the data works and gives me the output as expected. Can anyone see what's wrong with my code?
Thanks in advance :)
// function within view to fetch data
fetchData: function()
{
console.log('fetchData')
// Assign scope.
var $this = this;
// Set the colletion.
this.collection = new BookmarkCollection();
console.log(this.collection)
// Call server to get data.
this.collection.fetch(
{
cache: false,
success: function(collection, response)
{
console.log(collection)
// If there are no errors.
if (!collection.errors)
{
// Set JSON of collection to global variable.
app.userBookmarks = collection.toJSON();
// $this.loaded=true;
// Call function to render view.
$this.render();
}
// END if.
},
error: function(collection, response)
{
console.log('fetchData error')
console.log(collection)
console.log(response)
}
});
},
// end of function
Model and collection:
BookmarkModel = Backbone.Model.extend(
{
idAttribute: 'lineNavRef'
});
BookmarkCollection = Backbone.Collection.extend(
{
model: BookmarkModel,
//urlRoot: 'data/getBookmarks.php',
urlRoot: 'http://' + app.Domain + ':' + app.serverPort + '/data/getBookmarks.php?fromCrm=true',
url: function()
{
console.log(this.urlRoot)
return this.urlRoot;
},
parse: function (data, xhr)
{
console.log(data)
// Default error status.
this.errors = false;
if (data.responseCode < 1 || data.errorCode < 1)
{
this.errors = true;
}
return data;
}
});
You can make the requests using JSONP (read about here: http://en.wikipedia.org/wiki/JSONP).
To achive it using Backbone, simply do this:
var collection = new MyCollection();
collection.fetch({ dataType: 'jsonp' });
You backend must ready to do this. The server will receive a callback name generated by jQuery, passed on the query string. So the server must respond:
name_of_callback_fuction_generated({ YOUR DATA HERE });
Hope I've helped.
This is a cross domain request - no can do. Will need to use a local script and use curl to access the one on the other domain.
I am trying to set up a variant fetch method on my backbone model that will fetch the current model for a given user. This is available from the API on /api/mealplans/owner/{username}/current.
I have written the following model. I commented out the URL Root, as the prototype fetch call was simply using the urlRoot and I wanted to see if that was overriding the url parameter I passed in portions somehow.
var mealPlan = Backbone.Model.extend({
name: 'Meal Plan',
//urlRoot: '/api/mealplans',
defaults: {},
fetchCurrent: function (username, attributes, options) {
attributes = attributes || {};
options = options || {};
if (options.url === undefined) {
options.url = "/api/mealplans/owner/" + username + "/current";
}
return Backbone.Model.prototype.fetch.call(this, attributes, options);
},
validate: function (attributes) {
// To be done
return null;
}
});
I've seen this done, in some variations in other places, such as at backbone.js use different urls for model save and fetch - In that case the code is slightly different (I started with that and broke it down to make it easier for me to read.)
The options object has the url parameter in it fine when I pass it to fetch, but then it seems to ignore it!
I was assuming the same parameters to fetch as to save - This is not the case.
The method signature for fetch ONLY takes 'options' and not 'attributes', hence the url parameter wasn't found.
The model code should look a bit more like this..
var mealPlan = Ministry.Model.extend({
name: 'Meal Plan',
urlRoot: '/api/mealplans',
defaults: {
},
fetchCurrent: function (username, options) {
options = options || {};
if (options.url === undefined) {
options.url = this.urlRoot + "/owner/" + username + "/current";
}
return Backbone.Model.prototype.fetch.call(this, options);
},
validate: function (attributes) {
// To be done
return null;
}
});
I think it is better to override url() method, like below:
var mealPlan = Ministry.Model.extend({
name: 'Meal Plan',
urlRoot: '/api/mealplans',
//--> this gets called each time fetch() builds its url
url: function () {
//call the parent url()
var url=Backbone.Model.prototype.url.call(this);
//here you can transform the url the way you need
url += "?code=xxxx";
return url;
}
...
besides, in your example above I think there is a mistake and you should replace fetchCurrent by fetch
I have some trouble appending a token to the backbone url query string and hope you guys could help me out here. Three things to know,
There is a rest api that expects a token with each request
An nginx backend that does auth, serves the backbone app + proxy req to the api under /api
i'm a new to javascript + backbone :/
The backbone app actually reads the token from a cookie and I need to append this to the request url everytime backbone makes a call. I see this can be done by overriding backbone sync. but it troubles me in a few different things. like, this is what I do
console.log('overriding backbone sync');
var key ="token";
Backbone.old_sync = Backbone.sync
Backbone.sync = function(method, model, options) {
if (method === 'read') {
if (!(model.url.indexOf('?key=') != -1)) {
model.url = model.url + '?key=' + key;
}
} else {
old_url = model.url();
if (!(old_url.indexOf('?key=') != -1)) {
model.url = function() {
return old_url + '?key=' + key;
}
}
}
Backbone.old_sync(method, model, options);
};
model.url was returning a function when its not a "read" method and didn't know how to handle it well and the other trouble is when a consecutive request is made, the token is added twice. I tried to remove it with that indexOf stuff with no luck.
Is there a better way to do this ?
I don't think you need to override sync at all:
var globalKey = 'key123';
var urlWithKey = function(url, key) {
return function() {
return url + "?key=" + key;
};
};
var MyModel = Backbone.Model.extend({
url: urlWithKey('/my/url/', globalKey)
});
If you now create an object and save it, a POST request to my/url/?key=key123 is sent.
I guess you could also override the url method if this is the behavior you need for all of your Backbone models.
A general note: in Backbone most parameters, such as url can be a function or a value. I don't know why in your example it was a function once and a value in another case, but you always must be able to handle both ways if you override some of the internal functions. If you look at Backbone's sourcecode you will see that they use getValue to access these parameters:
var getValue = function(object, prop) {
if (!(object && object[prop])) return null;
return _.isFunction(object[prop]) ? object[prop]() : object[prop];
};
Update: Overloading the url method for all models could work like this:
var globalKey = 'key123';
(function() {
var baseUrl = Backbone.Model.prototype.url;
Backbone.Model.prototype.url = function() {
return this.baseUrl + "?key=" + globalKey;
};
})()
var MyModel = Backbone.Model.extend({
baseUrl: '/my/url/'
});
You could also leave the regular Backbone.Model as it is, and create your own base class. See http://documentcloud.github.com/backbone/#Model-extend for details.
Just set your URL like so:
url : function() {
return "/my/url" + this.key;
}
In your overridden .sync, you only need to set the key property.