Wait for another observable before proceeding

后端 未结 1 1161
忘掉有多难
忘掉有多难 2021-01-23 17:18

I don\'t know if I should post any code for this. But I will if required. I have an Angular2 directive, MyDirective and a service MyService

The

1条回答
  •  抹茶落季
    2021-01-23 17:55

    No, since the http calls are always asynchronous you can't synchronously wait for them.

    You can however instantiate the service with the ReflectiveInjector yourself and call the initialization before bootstrapping your app to be sure everything has loaded.

    In the bootstrap call just provide your MyService instance with the data.

    //import ... from ...
    import {MyService} from './my.service';
    
    let injector = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS, MyService]);
    var myService: MyService = injector.get(MyService);
    
    myService.init()
      .subscribe(data => {
        bootstrap(App, [
          HTTP_PROVIDERS,
          provide(MyService, {useValue: myService})
        ])
        .catch(err => console.error("error: ", err));
      });
    

    In your MyService add this init method returning an Observable for your data loading:

    init(): Observable {
      if (!this._initialized) {
        this._initialized = true;
        return this._http.get(this._url)
          .map(data => { 
            this._data = data.json();
            return this._data;
          });
      }
      else {
        console.log("Already initialized!");
      }
    }
    

    Plunker with a working example

    0 讨论(0)
提交回复
热议问题