Proposal: OnInit with Promise

Goal

I’d like to use Promise with OnInit. Similar implementation already exists on routerOnActivate.

OnActivate – ts

If routerOnActivate returns a promise, the route change will wait until the promise settles to instantiate and activate child components.

I want the component to wait its instantiation until the promise returned by ngOnInit resolved.

Example: (not works well)

@Component({
  selector: 'my-app',
  template: `
    <p>{{status}}</p>
  `,
})
export class App implements OnInit {

  ngOnInit() {
    return this.someAsyncProcess();
  }

  someAsyncProcess(): Promise<any> {
    // returns some promise
    ...
  }
}

Plunker

Problem

Currently ngOnInit has no return.

angular/dynamic_change_detector.ts at 42231f571947fbd2db5ea5692d3990470c019990 · angular/angular

angular/change_detection_jit_generator.ts at 42231f571947fbd2db5ea5692d3990470c019990 · angular/angular

Please let opinion! 😄

Thanks

3 thoughts on “Proposal: OnInit with Promise

  1. ngOnInit informs you that the component has been created and all the property bindings have been initialized. At this point it’s too late to stop anything because everything that matters has happened already.

    Guards like the one you are asking for should be available in the parents of component in question. We are still working through how this will work with a Router but even without the router a similar guard could be implemented using an ngIf that wraps the guarded component in the template of the parent component.