Angular 4:在承诺

时间:2017-10-15 08:49:46

标签: angular

我正在尝试在ngInit AppComponent的{​​{1}}中完成通话后配置我的路线

这是我的app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  entryComponents: [
    DummyComponent
  ]
})
export class AppComponent {
    routesLoaded: boolean = false
    constructor(private router: Router) {
        myCall().subscribe(() => {
            router.resetConfig([
                {
                    path: '', redirectTo: '/dummy', pathMatch: 'full'
                },
                {
                    path: 'dummy', component: DummyComponent
                }]
            )
            this.routesLoaded = true
        })
    }
}

和我的app.component.html

<div *ngIf="routesLoaded">
  <router-outlet></router-outlet>
</div>

它不起作用,我遇到以下错误:

core.es5.js:1020 ERROR Error: Uncaught (in promise): [object Object]
    at resolvePromise (zone.js:824)
    at resolvePromise (zone.js:795)
    at zone.js:873
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.es5.js:3881)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424)
    at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (zone.js:192)
    at drainMicroTaskQueue (zone.js:602)
    at <anonymous>

我想做的是可行的吗?还是我错过了什么? 如果我将router.resetConfig移到呼叫之外,它就可以正常工作。

2 个答案:

答案 0 :(得分:0)

您应立即致电resetConfig ngOnInit函数。

您可以使用APP_INITIALIZER提供程序来解析promise(在模块init之前)。 例如:

providers: [
    DataService,
    {
    provide: APP_INITIALIZER,
    useFactory: factory,
    deps: [DataService],
    multi: true
  }],

factory函数与myCall承诺:

export function factory(dataService: DataService) {
  return () =>  dataService.myCall().then((_result) => {
    dataService.myCallResult = _result;
  })
}

ngOnInit将在承诺解决后致电。

 ngOnInit() {
    this.myCallResult = this.dataService.myCallResult; //promise result
    this.router.resetConfig([
      {
        path: '', redirectTo: '/dummy', pathMatch: 'full'
      },
      {
        path: 'dummy', component: DummyComponent
      }
    ]);
  }

在这里查看我的例子:

https://stackblitz.com/edit/angular-bu8evj?file=app%2Fapp.component.html

答案 1 :(得分:-1)

你应该使用警卫(canActivate)。 在你获得路线之前(在守卫中)应该调用resetConfig