Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
79
Help us understand the problem. What is going on with this article?
@konpyu

ビューのレンダリングが始まる前に特定の処理を完了させたいとき

More than 5 years have passed since last update.

やり方はいろいろあると思います

ひとつは、$routeProviderのresolveを使う方法

あるURLに飛ぶ前に、必ず現在のユーザの情報をhttpで取ってきて$scopeに入れたい。
入れ終わってからビューを描画したいという状況だとします

index.html
<h2>demo</h2>
<div ng-app="app">
    <script type="text/ng-template" id="sample.html">
        <p>sample</p>           
        {{user}}
    </script>
    <div ng-view></div>
</div>

app.js
angular.module('app', ['ngRoute']).
config(function($routeProvider) {
    $routeProvider.when('/', {
        templateUrl: 'sample.html',
        controller: function($scope, currentUser){
            $scope.user = currentUser;
        },
        resolve: {
            currentUser: function($q, $http) {
                deferred = $q.defer()
                $http(url: '/yourappapi/v1/current_user', method: 'GET')
                .success(function(res){
                    deferred.resolve(res.user)
                });
                return deferred.promise;
            }
        }
    });
});

routeProviderのresolveオプションはcontrollerにinjectionされるオブジェクトのmapです
オブジェクトはpromiseを指定することになっており、このpromiseが解決したタイミングで
controllerにinjectionされます。
このため、API経由でユーザ情報を無事に取ってこれた後にcontroller内のコードが走ります。

実際には、良く使う初期化処理である場合は
resolveの処理をserviceに追い出してやった方が見通し良いでしょう

current_user_service.js
angular.module('app').factory('getCurrentUser', function($q, $http) {
    deferred = $q.defer();
    $http(url: '/yourappapi/v1/current_user', method: 'GET')
    .success(function(res) {
        deferred.resolve(res.user);
    });
    return deferred.promise;
});
$routeProvider.when('/', {
    templateUrl: 'sample.html',
    controller: function($scope, currentUser){
        $scope.user = currentUser;
    },
    resolve: {
        currentUser: function(getCurrentUser) { return getCurrentUser; }
    }
});


test

79
Help us understand the problem. What is going on with this article?
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
konpyu
software engineer
pieceofcake
cakes(ケイクス)とnote(ノート)を運営しています

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
79
Help us understand the problem. What is going on with this article?