Backbone Model save - this.model.get('id') undefined - backbone.js

Using this:
this.model.save(null, {
           success: function(model) {
               app.router.navigate('items/' + model.get('id'));
               this.render();
           }
       });
Has anyone got any ideas why model.get('id') would be undefined, yet model.id has the new id from the server?

The .get method on a Backbone model will retrieve an 'attribute' (ie. property) from the 'attributes' property (object) of the model. It will not retrieve properties on the model that are not part of those attributes - model.id is a property on the model itself.

The success callback takes three arguments - (model, response, options).
Try response.id or console.log out response.

Related

Looking to byepass a security for a webpage using AngularJS and Springboot

Using AngularJS  stateProvider with Springboot. So when user hits any page URL it comes to AngularJS controller firstly and then to Spring Controller which renders the page.
$stateProvider
        .state('registration', {
            url: '/registration',
            templateUrl: 'registration',
            controller: 'registrationController',
            controllerAs: 'registrationController',
             }); 
Inside Spring controller method-
#RequestMapping("/registration")
String VoterRegistrationPageHandler(ModelMap modal) {                
        return "registrationpage";
}
 
Also for the http security, security configurations are used for all the endpoints for ex. An endpoint for /api/user/** should be accessed by only a user with role as user. Adding to that I have provided the custome form for the authentication like below.
 
#Override
        protectedvoidconfigure(HttpSecurity http) throwsException {
                http.authorizeRequests()                        
                .antMatchers("/api/user/**").hasAnyRole("Admin","User")
                .and().formLogin()
                .loginPage("/login").usernameParameter("userName").passwordParameter("password")
                .and().csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
                
        }
Now I want that one of the template page which should not need the authentication by the user and hence I want to bye-pass the security configuration for that page so user should not be asked to login and directly the page should be displayed. Tried to add that in http security but did not work. Any suggestions please.
Adding the code how i added this in Security Configuration-
#Override
protectedvoidconfigure(HttpSecurity http) throwsException {
http.authorizeRequests()
.antMatchers("/registration").permitAll() ///newly added
.antMatchers("/api/user/**").hasAnyRole("Admin","User")
.and().formLogin()
.loginPage("/login").usernameParameter("userName").passwordParameter("password")
.and().csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}

how to disable specific dats from angular datepicker

var post1 = $http({
method: "POST",
url: "/Home/GetunAvailableDates",
dataType: 'json',
data: sub1,
headers: { "Content-Type": "application/json" }
});
var a = [];
post.then(function (d) {
if (d) {
for (var i = 0; i < d.data.length; i++) {
a.push(d.data[i].valueOf(Text).Text)
}
}
console.log("success");
}, function (d) {
$window.alert("Oops!! Something went wrong!!!!.");
});
this.selectedDates = a;
I'm currently working in mvc project.
I'm using AngularJs datepicker for my booking page. I need to disable dates which booking is unavailable.
I retrieve dates from database as list inside my booking.js file
My problem is how can bind that list of dates to angular datepicker. I tried so many ways but result was not good. guys help me how can i do that using angular.

Broadcast headers to all resources after calling another one resource

I built a rest api, now it's time to handle data with angular. To do that, I built a service to make a connection to my resources.
So I've :
angular.module("myServiceRest", ['ngResource'])
.factory("myService", function ($rootScope, $resource) {
var apiData = $resource(
"/api", {},
{
"getContains": {method: 'GET', isArray: false, url: "/api/users/:userid/:yearid/:groupeid/:levelid", headers: $rootScope.headers},
"getContain": {method: 'GET', isArray: false, url: "/api/Contains/:containid", headers: $rootScope.headers},
"postAuthTokens": {method: 'POST', url: "/api/auth-tokens"}
});
return {
getGroupesContenus: function (user_id, year_id, groupe_id, level_id) {
return apiData.getContains({userid: user_id, yearid: year_id, groupeid: groupe_id, levelid: level_id});
},
getContain: function (contain_id) {
return apiData.getContain({containid: contain_id});
},
postAuthTokens: function(userData) {
apiData.postAuthTokens(userData, function (data) {
console.log("success !");
$rootScope.headers = {
"Content-Type": "application/json",
"Authorization": "Basic ZWRnYXJrYW1kZW06TkVXVE9O",
"Accept": "application/json",
"X-Auth-Token": data.value
};
}, function (error) {
console.log(error.data);
})
}
}
});
Here I have 3 resources :
getContains: /api/users/:userid/:yearid/:groupeid/:levelid
getContain: /api/Contains/:containid
postAuthTokens: /api/auth-tokens
To get access to getContains and getContain (after logged in), the user need to set a token (X-Auth-Token) retrieved through postAuthTokens.
Basically, when the user log in, he calls the POST resource postAuthTokens, and retrieve his token (stored in a database) through data.value, and have to set that token in X-Auth-Token in order to continue.
For that, I created a $rootScope, and immediately when the user get log in, I set :
$rootScope.headers = {
"Content-Type": "application/json",
"Authorization": "Basic ZWRnYXJrYW1kZW06TkVXVE9O",
"Accept": "application/json",
"X-Auth-Token": data.value //Set the user token
};
But it doesn't work at all. It's like $rootScope.headers got reinitialize after calling post Auth Tokens, because, when the user log in I got this error in my Chrome console afterward:
angular.js:14328 Possibly unhandled rejection: {"data":{"error":{"code":500,"message":"Internal Server Error","exception":[{"message":"X-Auth-Token header is required","class":"Symfony\\Component\\Security\\Core\\Exception\\BadCredentialsException","trace":...
My $rootScope.headers wasn't set at all.
So how can I broadcast my $rootScope.headers to all resource headers after calling postAuthTokens ?
Instead of adding the headers to the root scope, add them to the $http service:
$http.defaults.headers.common['X-Auth-Token'] = data.value
They should then be added to all subsequent HTTP requests automatically

How to intercept $resource requests

Would there be a way to intercept requests in the $resource call?
I want to add an OAUTHv2 header to it, instead of specifying this for every resource model.
Currently I'm only able to intercept the response, as stated in the docs:
...
interceptor - {Object=} - The interceptor object has two optional
methods - response and responseError. Both response and responseError
interceptors get called with http response object. See $http
interceptors.
I know you can push a global interceptor on $http, but I don't want to include my Bearer token in any request outside API calls (security...)
Anybody who is doing OAUTHv2 must have come across this problem. A pity there is no standard way in Angular.JS...
Though, it's not obvious, there is a way to intercept $resource request.
Here is an example:
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Intercept resource request</title>
  <style type="text/css">.ng-cloak { display: none; }</style>
  <script src="angular.js"></script>
  <script src="angular-resource.js"></script>
  <script>
angular.module("app", ["ngResource"]).
  factory(
    "services",
    ["$resource", function ($resource)
    {
      return $resource(
"http://md5.jsontest.com/",
        {},
{
          MD5:
{
method: "GET",
params: { text: null },
then: function(resolve)
{
this.params.text = "***" + this.params.text + "***";
this.then = null;
resolve(this);
}
}
});
}]).
  controller(
    "Test",
    ["services", function (services)
    {
      this.value = "Sample text";
      this.call = function()
      {
        this.result = services.MD5({ text: this.value });
      }
    }]);
  </script>
</head>
<body ng-app="app" ng-controller="Test as test">
  <label>Text: <input type="text" ng-model="test.value" /></label>
  <input type="button" value="call" ng-click="test.call()"/>
  <div ng-bind="test.result.md5"></div>
</body>
</html>
How it works:
$resource merges action definition, request params and data to build a config parameter for an $http request.
A config parameter passed into an $http request is treated as a promise like object, so it may contain then function to initialize config.
Action's then function may transform request as it wishes.
The demo can be found at transform-request.html
Elsewhere I've already shown a similar approach used to cancel $resource request.
See also: Intercept angularjs resource request
You can use $http interceptors
You can pass them in options for $resource methods
Article on that: http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/

Kendo ComboBox not populating on REST GET

Trying to display "COLUMN_NAME" text in combobox. Here is the successful '200' response with parsed string from the browser:
[{"COLUMN_NAME":"Account","DATA_TYPE":"char"},"COLUMN_NAME":"Address","DATA_TYPE":"char"},...}]
Here is my js:
var dataSourceCustomers = new kendo.data.DataSource({
transport: {
read: {
url: "http://127.0.0.2:6080/arcgis/rest/services/Wks/WW/MapServer/exts/RestSOE/Search%20Parameters?searchType=CUSTOMER&f=",
dataType: "jsonp",
type: 'GET'
}
},
schema: {
data: ["COLUMN_NAME","DATA_TYPE"],
}
});
dataSourceCustomers.read();
The combobox however is blank. Thanks in advance!
The problem is the definition of schema.data that you define it as an array and this is not supported. In addition and according with you example of JSON you don't need it.
And in the ComboBox you define where on each item of the array is where you have the field for the Combo.
It should be like:
var dataSourceCustomers = new kendo.data.DataSource({
transport: {
read: {
url: "http://127.0.0.2:6080/arcgis/rest/services/Wks/WW/MapServer/exts/RestSOE/Search%20Parameters?searchType=CUSTOMER&f=",
dataType: "jsonp",
type : 'GET'
}
}
});
$("#combo").kendoComboBox({
dataSource : dataSourceCustomers,
dataTextField: "COLUMN_NAME"
})
BTW: Your example looks like JSON and not JSONP. Is it JSONP?

Resources