1

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)

2
  • What you call teechpadController looks like a service or factory. You're also logging heart, when you created a variable called h. I'd recommend using ngResource over $http if you're going to consume REST. And lastly, you'll get quicker answers if you create a jsfiddle.net or a plnkr.co or a jsbin.com that contains your best attempt. Commented Oct 8, 2013 at 20:34
  • I'm quite new here and I don't know jsfiddle or plnkr.co. Commented Oct 8, 2013 at 20:37

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Then, I want to see the results of the request on my index.html, so, just to see if everything works. What I have to do? just {{api}} in the index?
I hope my edit makes sense to you regarding to how to use the resulting data in your markup.
First of all , thanks! Second, I did what you say. I have changed the html according to your instrunctions. Then, I updated teechpadController.js adding what you wrote(I mean where you wrote javascript). At this point when I try to see the result, in index.html, I can only see {{apiResult}}. In fact the console(firebug) return me an error like: Error: api is not defined and then there are a lot of rows where there's mentionated @http. So I think I'm wrong with the customUrl variable and with appkey and app id. Can you help me once again?
If you need more about rest api documention, don't hesitate to ask me
plnkr.co/edit/xQRN1XYmfhthvmkTbJy8?p=preview This is as far as I can help you, this plunkr does not work due to security-reasons but if you take the code locally, you can test it out and try to understand the concepts.. also ofcourse you need to fix the id and also the Teech-API-keys/Teech-id (See the 3 TODOs)
0

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 :)

1 Comment

Sorry but I don't understand your answer, completely. The first step that I have to do is create a file "mycontroller.js" and then copy and paste var app = angular.module('TeechTest',[]).factory('$api', function($http){ ... }); var controller = app.controller('ctrl', ['$api', function($api){ ... }]); ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.