LoginSignup
4
7

More than 5 years have passed since last update.

AngularJSのfactory内でHTTPリクエストサンプル

Posted at

AngularJSのfactory内でHTTPリクエストを実行して、レスポンスが返ってきた後、controller側で継続の処理を実行する処理のサンプルです。備忘録として、残しておきます。

まずは、factory。ここでは、「dataService」という名前で作成しています。
appは通常通り、
var app = angular.module("app",[]);
で生成しています。

dataService.js
app.factory('dataService',['$http', '$q', function($http, $q){
    // Promiseオブジェクト
    var deffered = $q.defer();

    // ページ内のデータ
    var data = {};

    // ステータス
    var status = 'none';

    // メッセージ
    var message = '';

    var dataService = {};

    /**
     * ajaxで情報を取得
     * @param url
     */
    dataService.getData = function(url){
        //GETリクエスト
        $http.get(url, {
            headers: {
              'Content-type': 'application/json'
            }
        })

        .success(function(ret){
            if(ret['status']==='success'){
                data = ret['data'];
                status = ret['status'];
                // 成功
                deffered.resolve();
            } else {
                status = ret['status'];
                message = ret['message'];
                // エラー
                deffered.reject();
            }
        })
        .error(function(){
            status = 'error';
            message = '情報の取得に失敗しました';
            // エラー
            deffered.reject();
        });  
        return deffered.promise;
    };

    dataService.data = function(){
        return data;
    };

    dataService.status = function(){
        return status;
    };

    dataService.message = function(){
        return message;
    };

    return dataService;

}]);

続いて、このfactoryを利用するcontroller。

controller.js
app.controller("SampleController", ['$scope', '$rootScope', '$http', 'dataService', function ($scope, $rootScope, $http, dataService) {
    // リクエストのURL
    $scope.requestUrl = '/ajax_sample/getData';

    // dataServiceのgetDataを実行する処理
    $scope.getData = function(url){
        dataService.getData(url).then(function(){
            // service内のHTTP通信が終わったあとの処理
            $scope.data = dataService.data();
            $scope.status = dataService.status();
            $scope.message = dataService.message();
        });
    };

    $scope.getData($scope.requestUrl);

}]);

以上です!

4
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
7