0

I wonder what's the best way to configure a route which only purpose is to make use of a service call and then redirect.

I'm currently using this hack:

$routeProvider.when('/talks', { 
    template: '<div></div>', 
    controller: ['dateService', '$location', function(dateService, $location){
        var nextTalk = dateService.getNextTalkDate();
        $location.path('talks/' + nextTalk.format('MM') + '/' + nextTalk.format('YYYY'));
    }]
});

Currently I set the controller configuration to an inline controller implementation which has dependencies on the services and then does it's thing and redirects.

However, it feels a bit weird, since I have to set template to some dummy value because otherwise the controller would not be invoked at all.

It feels as if I'm stressing the controller property for something it wasn't intended for.

I guess there should be a way to run some view unrelated code that has access to services on a route. I could right my own $routeProvider I guess but that seems to be a bit heavy for something I would consider should be built in.

4

2 回答 2

1

There's no way to inject services into anywhere into a route. Whether it be redirectTo or template, any code in there is handled on the module level. This means that the module is loaded first and then when the application has boostrapped itself then the services and injection-level code is executed. So the controller is your best bet (since that does support injection).

Controller is used in a lot of areas in AngularJS and it should work fine for what you're trying to do. You can either handle the redirection like you do in there or you can setup three different routes that point to the same controller (where you build the page).

var handler = { controller : 'Ctrl' };
$routeProvider.when('/talks', handler).
               when('/talks/:month, handler).
               when('/talks/:month/:year', handler);

And if you do end up using redirection, then just use $location.path(url).replace(). This will make the history stack jump back one level and therefore that the redirection triggering URL won't be in your history.

于 2013-03-31T23:42:14.863 回答
1

看起来 '/talks' 有点抽象,因为它只是用于重定向到其他路由。那么如何设置这样的路由:

''/谈话/:月/:年'

其中 :month 和 :year 是可选的。如果没有给出月份或年份,您的服务将返回默认谈话。这可能是下一个话题。如果给定参数,您只需获取请求的数据。

所以不需要重定向。现在您指定控制器和所需的视图,并在范围上公开您的数据。(可选)将您的服务调用包装在一个承诺中并在 routeProviders 解析属性中解决它会更好。

这样可以确保只有在一切正常时视图才会改变。

希望有帮助!

于 2013-03-31T22:09:18.483 回答