Angular http 没有从 API 得到任何响应



我正在尝试从我在Ruby,Sinatra平台创建的本地API中获取Angular的任何信息。我确定 api 在端口 4567 上运行,因为如果我直接通过 Web 界面访问数据,我可以看到数据。当我这样做时,我看到这个(就在数字 0 旁边有一个小箭头,因此可以最小化对象的细节(:

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

如果我想查看 RAW 数据,我会得到这个:

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

在"另一边",我正在运行apache2和这个HTML文件:

    <!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>

你好.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;
    });
 });

为什么我看不到响应?我刚开始练习 Angular 并坚持在这里......

您的数据是一个对象数组,因此您可以输出如下: {{company[0].id}}

您可能遵循了一个使用 ng-repeat 的示例,如下所示:

<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/

使用 ng-init 执行你的 get 请求。在以下方法下实现 api 调用:

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;
         });
       }
 });

并在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>

最新更新