我正在使用 Angular 编写一个 Web 应用程序。
每次用户导航到该站点时,应用程序都必须在应用程序准备就绪之前执行一些服务器调用。
我试图定义一个必须在路由中解析的函数:
{path: '', resolve: {data: AppService}, children: [
{path: 'home', component: HomeComponent},,
{path: 'faq', component: FaqComponent},
{path: 'about', component: AboutComponent},
{path: 'contact', component: ContactComponent},
]}
Run Code Online (Sandbox Code Playgroud)
在AppServices中我有以下功能:
resolve(): Promise<any> {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('RESOLVING');
resolve();
}, 5000);
})
}
Run Code Online (Sandbox Code Playgroud)
这不起作用:用户导航到的页面在resolve调用之前显示。
问题:如何定义在应用程序准备就绪之前必须解析的函数?无论用户是否导航到应用程序,都必须调用此函数/,/foo /foo/bar并且只能在用户第一次导航到应用程序时调用此函数。
添加到应用程序提供商:
{
provide: APP_INITIALIZER,
useFactory: startupServiceFactory,
deps: [ Session ],
multi: true,
},
Run Code Online (Sandbox Code Playgroud)
在哪里:
export function startupServiceFactory(startupService: Session): Function {
return () => startupService.initialize();
}
Run Code Online (Sandbox Code Playgroud)
将startupService.initialize() 替换为您的方法。deps 包含您的服务所具有的任何依赖项,可以省略。
例子:
async initialize(): Promise<any> {
try {
if (!environment.production) {
this.user = await this.service.init();
this.role = this.user.role;
this.lang = this.user.lang;
this.translate.use(this.user.lang);
this.registerLocale();
this.navigate();
return;
}
this.router.navigateByUrl('/');
} catch (err) {}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1276 次 |
| 最近记录: |