Angular 2 服务的异步初始化

Async initialization of Angular 2 service

我有一个 Angular 2 服务需要在初始化时进行异步工作,并且在初始化完成之前不应该可用。

@Injectable()
export class Api {
    private user;
    private storage;

    constructor(private http: Http) {
        this.storage = LocalStorage;
        this.storage.get('user').then(json => {
            if (json !== "") {
                this.user = JSON.parse(json);
            }
        });        
    }

    // one of many methods
    public getSomethingFromServer() {
        // make a http request that depends on this.user
    }
}

就目前而言,此服务已初始化,并立即返回给使用它的任何组件。然后该组件在其 ngOnInit 中调用 getSomethingFromServer(),但此时 Api.user 未初始化,因此发送了错误的请求。

生命周期挂钩(OnInitOnActivate 等)不适用于服务,只能用于组件和指令,所以我不能使用它们。

存储来自 get() 调用的 Promise 需要依赖于用户等待它的所有不同方法,导致大量代码重复。

在 Angular 2 中进行服务异步初始化的推荐方法是什么?

您可以利用可观察对象通过 flatMap 运算符来做到这一点。如果用户不在,您可以等待它,然后链接目标请求。

这是一个示例:

@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(...);
      });
    }
  }
}

在研究了 Thierry 的答案之后,我发现它只能工作一次,但它确实让我走上了正确的道路。我不得不存储用户的承诺,并创建一个新的可观察对象,然后 flatMap-ed.

@Injectable()
export class Api {
  private userPromise: Promise<User>;

  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(...);
      });
    }
  }
}

这确保 flatMap 函数在每次调用时都能获得用户,而不是像 Thierry 的回答那样只是第一次。