【问题标题】:Angular2 resolver for main (bootstrapped) component?主要(引导)组件的Angular2解析器?
【发布时间】:2017-07-31 02:38:46
【问题描述】:

是否可以在 angular2 的主要组件之前解析服务?

【问题讨论】:

    标签: angular resolve


    【解决方案1】:

    在app的默认下执行resolve中的服务

    export const appRoutes: Routes = [
      {path:'', pathMatch: 'full', redirectTo: 'home'},
      { 
        path: 'home',
        component: AppComponent,
        resolve: function(){
             //your service call 
        },
      { 
        path: 'path1/:id',
        component: YourComponent,
        resolve: {
          someObject: ComponentResolve
        }
      }
    ];
    
    @Injectable()
    export class ComponentResolve implements Resolve<Interface> {
    
      constructor(private yourService: YourService) {}
    
      resolve(route: ActivatedRouteSnapshot) {
        return this.yourService.getMethod(route.params['id']);
      }
    

    【讨论】:

    • 我的引导主组件没有路由,path: '' 重定向到path: 'home', component: 'HomeComponent',AppComponent 由@NgModule({.....bootstrap:[AppComponent]}引导)`
    • 我有一个 main.ts 使用 platformBrowserDynamic().bootstrapModule(AppModule);
    • {path:'', pathMatch: 'full', redirectTo: 'home'},{path: 'home', component: HomeComponent} 以上都是主要路线
    • 您可以看到我的答案具有 resolve 属性吗?
    • 这个解决方案只是将'home'路由上的组件命名为AppComponent,这不会使其成为引导组件。
    【解决方案2】:

    在主路由文件中,在最顶层,您可以提及解析器名称,该名称将在最顶层组件加载之前解析(即引导组件)

        {
        path: '',
        resolve: AppComponentResolve,
        children: [
            {
                path: 'somePath',
                component: SomeCOmponent
            }]
        }
    

    并将解析器作为可注入组件添加到 appComponent 文件中

        @Injectable()
        export class AppComponentResolve implements Resolve<any> {
    
        resolve(){
          //return resolved data
         }
        }
    

    【讨论】:

      猜你喜欢
      • 2017-04-21
      • 2016-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-26
      • 2017-09-16
      • 1970-01-01
      • 2015-07-25
      相关资源
      最近更新 更多