2016-11-08 83 views
0

您好,我需要使用REST服务来显示网站(200,404等)的响应。

我创建了一个局部的代码,但我不知道如何显示结果

这是JS

angular.module('demo', []) 
.controller('Hello', function($scope, $http) { 
    $http ({ 
     method: 'GET', 
     url: 'http:/www.google.com' 
    }). 
     then(function(response) { 
      $scope.greeting = response.data; 
     }); 
}) 

,这是HTML

<body> 
    <div ng-controller="Hello"> 
     <p>Result = {{greeting.content}}</p> 
    </div> 
    </body> 

</html> 

感谢您的帮助。

+0

检查文档https://docs.angularjs.org/tutorial – mcranston18

回答

0

responseIHttpPromise<T>,其延伸IPromise<IHttpPromiseCallbackArg<T>>

这个界面看起来是这样的:

interface IHttpPromiseCallbackArg<T> { 
    data?: T; 
    status?: number; 
    headers?: IHttpHeadersGetter; 
    config?: IRequestConfig; 
    statusText?: string; 
} 

所以,你可以访问你需要什么: response.status

与您的代码:

angular 
 
    .module('demo', []) 
 
    .controller('Hello', HelloController) 
 

 
function HelloController($scope, $http) { 
 
    $http({ 
 
     method: 'GET', 
 
     url: 'http://enable-cors.org' 
 
    }) 
 
    .then(function(response) { 
 
     var text = "The status: " + response.status; 
 
     
 
     $scope.directResponse = response; 
 
     $scope.greeting = {content: text}; 
 
     $scope.someVariable = text; 
 
    }); 
 
    
 
} 
 

 
/* 
 
var $http = angular.injector(["ng"]).get("$http"); 
 

 
$http.get("http://enable-cors.org/").then(function(response) { 
 
    console.log(response.status); 
 
}); 
 
*/
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app="demo" ng-controller="Hello"> 
 
    <p>Status = {{directResponse.status}}</p> 
 
    <p>Result = {{greeting.content}}</p> 
 
    <p>Result = {{someVariable}}</p> 
 
</div>

+0

我试图改变,但没有发生 – nowaySync

+0

您的URL(http:/www.google.com)是错误的(只有一个斜杠)。你需要设置CORS来查看状态码。我用于测试目的:http://enable-cors.org/ –

+0

我已尝试此代码,但没有运行:angular.module('demo',[]) .controller('Hello',function($ scope, (函数(响应){console.log(response.status);} }响应){ $ scope.greeting =“我的数据:”+ response.data +“状态:”+ response.status; }); }); – nowaySync

0

你应该真的把你的$ http调用放到一个单独的服务中,并将它注入到控制器中。

所以是这样的:

angular.module('demo') 
.factory('greetingService', function($http) { 
    this.getGreeting = function() { 
     return $http ({ 
      method: 'GET', 
      url: 'http:/www.google.com' 
     }).then(function(response) { 
      return response.data 
     }); 
    } 
}; 

然后注入服务为您的控制器,并呼吁greetingService.getGreeting,然后设置你的$范围变量的结果。

另请确保您的请求中包含正确的标题。

+0

虽然这是一个很好的做法,在一个体面大小的项目中结合使用数据模型处理,但我不明白为什么它是必须在单独的服务中包装'$ http',而不是与这个问题相关,'$ http'本身也是一项服务。 – Icycool