Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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

}]);

以上です!

_takeshi_24
株式会社OneSmallStepの代表取締役CTOです。 https://twitter.com/_takeshi_24
https://1smallstep.jp
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした