Share Coding

Tutorials, Problems, Stuffs …

Category Archives: AngularJS

AngularJS – Cross Domin Get data by $resource

For reference:

http://docs.angularjs.org/api/ngResource.$resource

Required:

http://code.angularjs.org/1.2.0rc1/angular-resource.js

Module Configuration:

var myApp = angular.module('MyApp', ['ngResource']);
myApp.config(['$routeProvider', ,'$httpProvider', function($routeProvider, $httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
    ....
  }
]);

function: $resource(url[, paramDefaults][, actions]);

var User = $resource('http://localhost:port/sil/SilUserAuth.svc/Login', {port:':59217'}, { });
User.get({
       name: document.loginForm.email.value,
       password: document.loginForm.password.value
}, function (data) {
       alert(JSON.stringify(data));
});

Result on Firebug View:

GET http://localhost:59217/sil/SilUserAuth.svc/Login?name=abc&password=abc   200s OK 12ms

In ASP.NET MVC 4:

<script type="text/javascript" src="@Url.Content("~/Scripts/angular.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/angular-resource.js")"></script>

Set httpProtocol on Web.config

    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
      </customHeaders>
    </httpProtocol>

Problem 1

OPTIONS xxxxxxxxx (405 Method Not Allowed)

Solution
Remove the header from all requests :

"delete $httpProvider.defaults.headers.common['X-Requested-With'];"

Problem 2

Angularjs Error: destination.push is not a function

Solution
Define action type get / query / update / delete and  add isArray: true:

    var Papers = $resource('http://localhost:port/Sil/SilUserPaper.svc/UserPapers/:id', { port: ':59217' }, {
        get: { method: 'GET', params: {}, isArray: true }
    });
    Papers.get({
        id: 2
    }, function (data) {
        $scope.papers = data;
    });
Advertisements