2016-11-08 14 views
0

こんにちは私は、ウェブサイト(200,404など)からのレスポンスをRESTサービスを使って表示する必要があります。

私は部分的なコードを作成しましたが、私はこれは、JS

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

ある結果

を表示する方法を知らないとこれは

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

</html> 

おかげで助けを求めhtmlです。

+0

ドキュメントを確認するhttps://docs.angularjs.org/tutorial – mcranston18

答えて

0

responseは、IPromise<IHttpPromiseCallbackArg<T>>を拡張するIHttpPromise<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)が間違っています(スラッシュは1つだけです)。 CORSを設定してステータスコードを表示する必要があります。私はテスト目的のために使用しました:http://enable-cors.org/ –

+0

私はこのコードを試してみましたが、実行していません:angular.module( 'demo'、[]) .controller( 'Hello'、function($ scope、 $ http.get( "機能(応答){ console.log(応答。状態); })。 次に(機能(応答){ $ 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

関連する問題