AngularJS - routeProvider resolve calling a service method

前端 未结 2 1561
感情败类
感情败类 2021-02-05 07:58

I\'ve created a service which checks the user login state (log the user in if token exists, otherwise redirect to login page).

Originally I called this service through t

相关标签:
2条回答
  • 2021-02-05 08:05

    Adding to @Ajay's response, you can use a string rather than a standard property name, which will help with minification:

    resolve: {
        'myVar': function (repoService) {
            return repoService.getItems().then(function (response) {
                return response.data;
            });
        }
    }
    
    0 讨论(0)
  • 2021-02-05 08:30

    service are singletons means there are initialized only one but time but if you simply return from service it will be called one time but if you return a function from service it will be called again and again .See Below Sample for working

    var app = angular.module('ajay.singhApp', [])
      .config(['$routeProvider', function($routeProvider) {
        $routeProvider
          .when('/view1', {
            templateUrl: 'views/main.html',
            controller: 'MainCtrl',
            resolve: {
                myVar: function (repoService) {
                    return repoService.getItems().then(function (response) {
                        return response.data;
                    });
                }
            }
          })
            .when('/view2', {
                templateUrl: 'views/main.html',
                controller: 'MainCtrl'
            })
          .otherwise({
            redirectTo: '/view1'
          });
      }]);
    
    
    app.factory('repoService', function ($http) {
        return {
            getItems: function () {
                return $http.get('TextFile.txt');
            }
        };
    });
    
    0 讨论(0)
提交回复
热议问题