2016-11-10 69 views
0

我有以下几种类型: DataService - 使用signalr集线器从服务器获取数据。 AppComponent - 这是我主应用程序的入口点如何在我的信号服务初始化之前推迟加载组件?

数据服务构造函数如下。

constructor(private http: Http) { 
    var hub = $.connection.spwHub; 
    hub.client.loadEmployees = this.loadEmployees; 
    $.connection.hub.start().done(() => { 
     ... 
    }); 
} 

我AppComponent如下:

constructor(service: DataService) {  
    this.company = service.getCompany(); 
    service.getEmployees().then(employees => this.employees = employees); 
    this.departments = service.getDepartments(); 
} 

我得到的当然是下面的错误,因为由集线器连接之前枢纽异步调用至今未归。

EXCEPTION:./AppComponent类中的错误AppComponent_Host - 内联模板:0:0由:SignalR:Connection尚未完全初始化。使用.start()。done()或.start()。fail()在连接启动后运行逻辑。

在AngularJs2中处理这个问题的最佳方法是什么?

回答

0

您可以使用APP_INITIALIZER挂钩在应用程序的其余部分运行之前执行逻辑,获取准备好的东西,无论如何。

在你app.module.ts(或任何你的主要模块):

import { APP_INITIALIZER, NgModule }  from "@angular/core"; 
export function init_app(employeeService: EmployeeService) { 
    return() => employeeService.getEmployees(); 
} 

@NgModule({ 
    <...> 
    providers: [EmployeeService, { 
     provide: APP_INITIALIZER, 
     useFactory: init_app, 
     deps: [ EmployeeService ], 
     multi: true 
    }] 
}) 
export class AppModule { } 

服务返回一个承诺,其将被自动处理:

getEmployees() { 
    return <...function stuff ...> 
      .toPromise(); 
} 

而这里的github问题,这是记录在案(没有关于angular.io站点的文档):https://github.com/angular/angular/issues/9047

+0

我还不确定。我的意思是我想要一个随机函数来处理信号。我可以只是$ .connection.hub.start()。done(()=> {...});但是,这打破了目的。我不想从AppComponent外部加载数据。我不仅需要最初运行一些代码,还必须在加载应用程序组件之前返回代码。 – jwize

0

搜索我没有找到任何东西,我给出了这样的想法,即不需要加载的组件应该可以默认推迟。这意味着答案是毫不费力的。

// start.component.ts 
constructor() { 
    // Start the connection 
    var hub = $.connection.spwHub; 
    $.connection.hub.start().done(() => { 
     // This loads the next component and runs the constructor 
     this.initialized = true; 
    }); 
} 

// start.component.html 
<div *ngIf="initialized"> 
    <main-component></main-component> 
<div> 

// This type is lazy loaded as soon as the initialized equals true. 
// main.component.ts 
constructor(employeeService: EmployeeService) { 
    // Finally, load the needed data. 
    this.employees = employeeService.getEmployees(); 
} 
相关问题