Async initialization of Angular 2 service

后端 未结 2 389
执念已碎
执念已碎 2021-02-05 07:12

I have an Angular 2 service that needs to do async work when it is initalized, and should not be usable before this initialization has been completed.



        
2条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-05 07:34

    After working with Thierry's answer for a bit, I discovered that it would only work once, but it did set me on the right path. I had to instead store the promise of the user, and create a new observable which is then flatMap-ed.

    @Injectable()
    export class Api {
      private userPromise: Promise;
    
      constructor(private http: Http) {
        this.userPromise = LocalStorage.get('user').then(json => {
          if (json !== "") {
            return JSON.parse(json);
          }
          return null;
        });        
      }
    
      public getSomethingFromServer() {
          return Observable.fromPromise(this.userPromise).flatMap((user) => {
            return this.http.get(...).map(...);
          });
        }
      }
    }
    

    This ensures that the flatMap function gets the user every time it is called, instead of just the first time, as in Thierry's answer.

提交回复
热议问题