我有一个 Angular2 服务需要在初始化时执行异步工作,但在初始化完成之前它不应该可用。
@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
}
}
按照目前的情况typescript异步执行,服务被初始化并立即返回到使用它的任何组件。 然后该组件在其 ngOnInit 中调用 getSomethingFromServer(),但此时 Api.user 尚未初始化,因此发送了错误的请求。
生命周期挂钩(OnInit、OnActivate 等)不适用于服务,仅适用于组件和指令,因此我无法使用它们。
从 get() 调用存储 Promise 需要依赖用户等待它的所有不同方式typescript异步执行,从而导致大量代码重复。
在 Angular2 中进行服务异步初始化的推荐方法是什么?
发表评论