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

后端 未结 5 2259
星月不相逢
星月不相逢 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 06:00

    Option 1: $http service

    AngularJS provides the $http service that does exactly what you want: Sending AJAX requests to web services and receiving data from them, using JSON (which is perfectly for talking to REST services).

    To give an example (taken from the AngularJS documentation and slightly adapted):

    $http({ method: 'GET', url: '/foo' }).
      success(function (data, status, headers, config) {
        // ...
      }).
      error(function (data, status, headers, config) {
        // ...
      });
    

    Option 2: $resource service

    Please note that there is also another service in AngularJS, the $resource service which provides access to REST services in a more high-level fashion (example again taken from AngularJS documentation):

    var Users = $resource('/user/:userId', { userId: '@id' });
    var user = Users.get({ userId: 123 }, function () {
      user.abc = true;
      user.$save();
    });
    

    Option 3: Restangular

    Moreover, there are also third-party solutions, such as Restangular. See its documentation on how to use it. Basically, it's way more declarative and abstracts more of the details away from you.

提交回复
热议问题