简体   繁体   中英

Make a get request with restful api in angularjs

It's my first question here, sorry in advance if there's a discussion of what i'm going to ask, already. I'm new to angularjs and I'm pretty sure this is not a big problem, but I don't understand what I have to do. I'm working with API teech.io and I would like to get some experience to learn how to use them. My problem is this: make a GET request via http (each user has an app key and an app Id), for example to materials. The documentation of materials says this:

A GET to /materials/:id fetches the material object.

GET /materials/:id HTTP/1.1 Host: api.teech.io Teech-Application-Id: [app ID] Teech-REST-API-Key: [API key]

<!DOCTYPE html>
<html>
<head>

<!-- INCLUDE REQUIRED THIRD PARTY LIBRARY JAVASCRIPT AND CSS -->
    <script type="text/javascript" src="js/angular.min.js"></script>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/bootstrap-responsive.min.css">
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript" src="teechpadController2.js"></script>
</head>
<body>

the app.js is this one

var app = angular.module('TeechTest',[]);

The teechpadController is this

teechpad.factory('$api', function($http) {
  var defaults = {
   method: null,
   url: null,
   headers: {
    'Teech-REST-API-Key': api.teech.io.apikey,
    'Teech-Application-Id': api.teech.io.appid.
   }
  };

  var req = function(method, url, config) {
   defaults.method = method;
   defaults.url = 'http://api.teech.io' + url;
   var h = angular.extend({}, defaults, config);
   console.log(heart);     
   return $http(heart);
  };

  return {
   get: function(url, config) {
    return req('GET', url, config);
   },

   put: function(url, data, config) {
    defaults['Content-Type'] = 'application/json';
    defaults['data'] = data;
    return req('PUT', url, config);
   },

   post: function(url, data, config) {
    defaults['Content-Type'] = 'application/json';
    defaults['data'] = data;
    return req('POST', url, config);
   },

   delete: function(url, config) {
    return req('DELETE', url, config);
   }
  }



 });

What I understood till now is that teechpadcontroller re-define the PUT-POST-DELETE-GET methods. Now, How can I use, for example, get method in my controller? Or Should I create an other controller and then use $app there? Sorry again for everything, I'm very new here and in angularjs. Last but not least, I work with JSON object(I think it was clear already)

In your Controller (where you inject this factory) you could use this factory called $api.

The exposed functions to this $api is the four functions returned in the returncaluse:

return {
    get: function(url, config) {
      ...
    },

    put: function(url, data, config) {
      ...
    },

    post: function(url, data, config) {
      ...
    },

    delete: function(url, config) {
      ...
    }
}

so in your own controller you could use it something like this:

JavaScript

angular.module('myModule',['TechTest']).controller('myCtrl',function($api){
    var customUrl = "/PATH/TO/ENDPOINT",
        customConfig = {}; // might not be needed.
    $api.get(customUrl, customConfig).success(function(data){
        $scope.apiResult = data;
    });
})

HTML (which needs to know about your controller per usual)

 <!-- include scripts -->
 <body ng-app="myModule">
    <div ng-controller="myCtrl">
        <div>{{apiResult}}</div>
    </div>
</body>

I hope I did not missunderstood your quetion.

Now, How can I use, for example, get method in my controller?

You can use your '$api' inside any controller you define by adding it to the injectables of that controller through

var app = angular.module('TeechTest',[]).factory('$api', function($http){ ... });
var controller = app.controller('ctrl', ['$api', function($api){ ... }]);

and then call your 'get' method by going: $api.get( ... ); inside your controller.

Watch out, you've defined 'h' and 'heart' on two different lines, this might just be a typo but it might trip you up!

Your function call to $api.get( ... ); will return asynchronously and you will get the result inside either:

$api.get( ... ).success(function(response){ console.log(response); }); //success
$api.get( ... ).error(function(response){ console.log(response); }); //failure

This is a deferred callback - look into the promise API for more in depth details. You may also want to look into resetting the defaults object every time so you guarantee you're working with a clean object each function call.

Any incorrectness then say and I'll update my answer :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM