问题描述
我正在将我的应用切换到新的路由 DSL.具体来说,我想用 preEnter
做这样的事情:
I'm switching my app over to the new routing DSL. Specifically, I want to do something like this with preEnter
:
final RouteInitializerFn routes =(Router router, ViewFactory views) {
views.configure({
'chat': ngRoute(
path: '/chat',
// authService.requireState returns a Future<bool>, and may invoke an HttpRequest
preEnter: (RoutePreEnterEvent e) => e.allowEnter(authService.requireState(LOGGED_IN)),
view: 'views/chat.html'),
'login': ngRoute(
path: '',
defaultRoute: true,
view: 'views/login.html')
});
}
这将在模块中配置如下:
This would be configured in the module as follows:
value(RouteInitializerFn, routes);
如果你错过了,我在 RouteInitializerFn
中引用了一个可注入的 authService
.这是不可能的,因为 RouteInitializerFn
是一个函数而不是一个类,所以不能注入任何东西.如果我将 routes
函数封装在一个类中,我不确定如何配置 RouteInitializerFn
,所以我有点进退两难.
In case you missed it, I'm referencing an injectable authService
within the RouteInitializerFn
. This isn't possible since RouteInitializerFn
is a function and not a class, so nothing can be injected into it. If I encapsulated the routes
function within a class, I'm not sure how I could configure RouteInitializerFn
, so I'm in a bit of a quandary.
推荐答案
我找到了一个非常酷的解决方案.事实证明,如果在满足 typedef 的类上定义 call
方法,则可以将其配置为 typedef 的实现.非常很酷.这是我的解决方案:
I found a pretty cool solution to this problem. Turns out, if you define a call
method on a class that satisfies a typedef, you can configure it as an implementation of the typedef. Very cool. Here is my solution:
class Routes
{
final UserService _userService;
Routes(this._userService);
void call(Router router, ViewFactory views)
{
views.configure({
'chat': ngRoute(
path: '/chat',
preEnter: (RoutePreEnterEvent e) => e.allowEnter(this._userService.requireUserState(UserService.LOGGED_IN)),
view: 'views/chat.html'
),
'login': ngRoute(
path: '',
defaultRoute: true,
view: 'views/login.html'
)
});
}
}
这是它在模块中的配置方式:
and this is how it's configured within the module:
// old syntax
type(RouteInitializerFn, implementedBy: Routes);
// new syntax
bind(RouteInitializerFn, toImplementation: Routes);
这篇关于如何将服务注入 RouteInitializerFn(新路由 DSL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!