How to access the services from RESTful API in my angularjs page?

后端 未结 5 2257
星月不相逢
星月不相逢 2020-12-04 05:20

I am very new to angularJS. I am searching for accessing services from RESTful API, but I didn\'t get any idea. How can I do that?

5条回答
  •  一向
    一向 (楼主)
    2020-12-04 05:54

    Welcome to the wonderful world of Angular !!

    I am very new to angularJS. I am searching for accessing services from RESTful API but I didn't get any idea. please help me to do that. Thank you

    There are two (very big) hurdles to writing your first Angular scripts, if you're currently using 'GET' services.

    First, your services must implement the "Access-Control-Allow-Origin" property, otherwise the services will work a treat when called from, say, a web browser, but fail miserably when called from Angular.

    So, you'll need to add a few lines to your web.config file:

    
      ... 
      
        
        
        
        
            
                
                
            
        
      
      ... 
    
    

    Next, you need to add a little bit of code to your HTML file, to force Angular to call 'GET' web services:

    // Make sure AngularJS calls our WCF Service as a "GET", rather than as an "OPTION"
    var myApp = angular.module('myApp', []);
    myApp.config(['$httpProvider', function ($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }]);
    

    Once you have these fixes in place, actually calling a RESTful API is really straightforward.

    function YourAngularController($scope, $http) 
    {
        $http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
            .success(function (data) {
            //  
            //  Do something with the data !
            //  
        });
    }
    

    You can find a really clear walkthrough of these steps on this webpage:

    Using Angular, with JSON data

    Good luck !

    Mike

提交回复
热议问题