Async initialization of Angular 2 service

后端 未结 2 387
执念已碎
执念已碎 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:32

    You could leverage an observable to do that with the flatMap operator. If the user isn't there, you could wait for it and then chain the target request.

    Here is a sample:

    @Injectable()
    export class Api {
      private user;
      private storage;
      private userInitialized = new Subject();
    
      constructor(private http: Http) {
        this.storage = LocalStorage;
        this.storage.get('user').then(json => {
          if (json !== "") {
            this.user = JSON.parse(json);
            this.userInitialized.next(this.user);
          }
        });        
      }
    
      // one of many methods
      public getSomethingFromServer(): Observable<...> {
        // make a http request that depends on this.user
        if (this.user) {
          return this.http.get(...).map(...);
        } else {
          return this.userInitialized.flatMap((user) => {
            return this.http.get(...).map(...);
          });
        }
      }
    }
    

提交回复
热议问题