<h1>Example: CORS Ajax Primise</h1>
<p>CORS(Cross-Origin Resource Sharing)を使ったPromiseの使い方についてです。非同期でjsonを取得しメッセージを表示します。</p>
<div ng-app="myApp">
  <div ng-controller="myController">
    <button ng-click="get_data()">メッセージを取得</button>
    <p>{{ status }}</p>
    <p>{{ message }}</p>
  </div>
</div>
@import "bourbon";

body {
  padding: 1.5rem;
}
View Compiled
var service = angular.module("customServices", []);
service.factory('myService', ['$q', '$http', function($q, $http) {
  return {
    data: function(){
      //リクエスト内容
      var req = {
        method: 'GET',
        //url: 'http://api.nukos.kitchen/index.json',
        url: 'https://dk4mh7oqsj.execute-api.ap-northeast-1.amazonaws.com/prod',
        responseType: 'json'
      }
      
      //プロミスオブジェクトを返す
      return $http(req);
    }
  }
}]);

var app = angular.module('myApp', ['customServices']);
app.controller('myController', ['$scope', '$q', 'myService', function($scope, $q, myService){
  
  //データを取得後、メッセージを表示します
  $scope.get_data = function(){
    promise = myService.data();
    
    promise.then(function(strs){
      //成功時
      console.log(strs);
      $scope.status = strs.status;
      $scope.message = strs.data.message;
    });
  }
}]);

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js