Home Angular http get no response from api
Reply: 2

Angular http get no response from api

quant
1#
quant Published in 2017-11-14 22:49:48Z

I am trying to get any information with Angular from the local api that I have created in Ruby, Sinatra platform. I am sure that the api is running on the port 4567 since I can see the data if i access m it directly through web interface. When I do that I see this (just next to the number 0 there is like a small arrow so it is possible to minimize the details of the object):

  0
 id "1"
 name   "Company-A21"
 address    "Gany-A11"

If I want to see RAW data I get this:

[{"id":"1","name":"Company-A21","address":"Gany-A11"}]

On the "other side" I am running apache2 and this HTML file:

    <!doctype html>
<html >
    <head>
        <title>Hello AngularJS</title>
        <script src="hello.js"></script>
    </head>

    <body>
        <div ng-controller="Hello">
            <p>The ID is {{company.id}}</p>
            <p>The content is {{company.name}}</p>
        </div>
    </body>
</html>

And the hello.js:

angular.module('demo', [])
.controller('Hello', function($scope, $http){

    $http.get('http://localhost:4567/api/v1/companies/2').
    then(function(response) {
            $scope.company = response.data;
    });
 });

Why I can not see response? I just started to practice Angular and I stuck here...

Ronnie
2#
Ronnie Reply to 2017-11-15 00:05:03Z

Your data is an array of objects so you'd output it like: {{company[0].id}}

You probably followed an example using ng-repeat which would look something like this:

<div ng-repeat="company in companies">
   <p>The ID is {{company.id}}</p>
    <p>The content is {{company.name}}</p>
 </div>

https://jsfiddle.net/ojzdxpt1/21/

Syedur
3#
Syedur Reply to 2017-11-15 05:31:43Z

Use ng-init to execute your get request. Implement your api call under a method:

angular.module('demo', [])
.controller('Hello', function($scope, $http){
    $scope.getCompany = function(){
       $http.get('http://localhost:4567/api/v1/companies/2').
         then(function(response) {
            $scope.company = response.data;
         });
       }
 });

and use it in ng-init:

  <!doctype html>
<html >
    <head>
        <title>Hello AngularJS</title>
        <script src="hello.js"></script>
    </head>

    <body>
        <div ng-controller="Hello" ng-init="getCompany()">
            <p>The ID is {{company.id}}</p>
            <p>The content is {{company.name}}</p>
        </div>
    </body>
</html>
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.304261 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO