Angular 角度|和#xA0;如何在解析应用程序之前初始加载数据?

Angular 角度|和#xA0;如何在解析应用程序之前初始加载数据?,angular,promise,Angular,Promise,我正在使用Angular编写一个web应用程序 每次用户导航到该站点时,应用程序都必须在准备就绪之前执行一些服务器调用 我试图定义一个必须在路由中解析的函数: {path: '', resolve: {data: AppService}, children: [ {path: 'home', component: HomeComponent},, {path: 'faq', component: FaqComponent}, {path: 'about', component:

我正在使用Angular编写一个web应用程序

每次用户导航到该站点时,应用程序都必须在准备就绪之前执行一些服务器调用

我试图定义一个必须在路由中解析的函数:

{path: '', resolve: {data: AppService}, children: [
   {path: 'home', component: HomeComponent},,
   {path: 'faq', component: FaqComponent},
   {path: 'about', component: AboutComponent},
   {path: 'contact', component: ContactComponent},
]}
在AppServices中,我具有以下功能:

  resolve(): Promise<any> {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        console.log('RESOLVING');
        resolve();
      }, 5000);

    })
  }
resolve():承诺{
返回新承诺((解决、拒绝)=>{
设置超时(()=>{
console.log('RESOLVING');
解决();
}, 5000);
})
}
这不起作用:在调用
resolve
之前,将显示用户导航到的页面

问题:如何定义在应用程序准备就绪之前必须解决的函数?无论用户导航到
/
/foo
/foo/bar
都必须调用此函数,并且只能在用户第一次导航到应用程序时调用此函数。

添加到应用程序提供程序:

{
        provide: APP_INITIALIZER,
        useFactory: startupServiceFactory,
        deps: [ Session ],
        multi: true,
    },
其中:

export function startupServiceFactory(startupService: Session): Function {
    return () => startupService.initialize();
}
将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) {}
    }
async initialize():承诺{
试一试{
if(!environment.production){
this.user=等待this.service.init();
this.role=this.user.role;
this.lang=this.user.lang;
this.translate.use(this.user.lang);
this.registerLocale();
这个。导航();
返回;
}
this.router.navigateByUrl('/');
}捕获(错误){}
}

您可以使用canActivate gurard,它可以在路由上返回布尔值的可观测值

import { Injectable } from '@angular/core';
import { CanActivate, Router }    from '@angular/router';
import { Observable } from 'rxjs/Observable';

    @Injectable()
    export class AuthGuard implements CanActivate {
      constructor(private router: Router) { }

      canActivate(): Observable<boolean> {
            //Ajax call and other logic
            return Observable.of(true)
      }
    }



{path: '', canActivate: [AuthGuard], children: [
   {path: 'home', component: HomeComponent},,
   {path: 'faq', component: FaqComponent},
   {path: 'about', component: AboutComponent},
   {path: 'contact', component: ContactComponent},
]}
从'@angular/core'导入{Injectable};
从'@angular/Router'导入{CanActivate,Router};
从“rxjs/Observable”导入{Observable};
@可注射()
导出类AuthGuard实现了CanActivate{
构造函数(专用路由器:路由器){}
canActivate():可观察的{
//Ajax调用和其他逻辑
可观测的返回值(真)
}
}
{路径:'',可激活:[AuthGuard],子项:[
{path:'home',component:HomeComponent},,
{路径:'faq',组件:FaqComponent},
{path:'about',component:AboutComponent},
{路径:'contact',组件:ContactComponent},
]}

谢谢。“initialize”函数必须返回一个承诺,对吗?这正是我想要的。谢谢非常感谢!这将在应用程序初始化时仅调用一次,而不是每次用户导航到该站点时。它将被调用。上面的例子是自动登录我的用户到我的应用程序,以防他们的会话是实时的。这个方法是可行的,但在我看来有点粗糙。我不认为canActivate是为这个用例构建的。我还认为每次路由更改时都会调用canActivate(可能是错误的),我认为不会在用户每次导航到站点时调用APP_初始值设定项。