Angular 2服务的异步初始化 [英] Async initialization of Angular 2 service

查看:148
本文介绍了Angular 2服务的异步初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

@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尚未初始化,因此发送了错误的请求.

As it currently stands, this service is initialized, and returned immediately to any component that uses it. That component then calls getSomethingFromServer() in its ngOnInit, but at that point Api.user is not initialized, and therefore the wrong request is sent.

生命周期挂钩(OnInitOnActivate等)不适用于服务,仅适用于组件和指令,因此我无法使用它们.

The lifecycle hooks (OnInit, OnActivate, etc) does not work with services, only components and directives, so I cannot use those.

通过get()调用存储Promise将需要所有依赖用户的不同方法来等待它,从而导致大量代码重复.

Storing the Promise from get() call would require all the different methods that depend on user to wait for it, causing a lot of code duplication.

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

What is the recommended way to do async initialization of services in Angular 2?

推荐答案

在处理了Thierry的答案后,我发现它只能使用一次,但确实使我走上了正确的道路.相反,我必须存储用户的承诺,并创建一个新的可观察对象,然后进行flatMap -ed.

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<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的回答那样只是第一次获得用户.

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.

这篇关于Angular 2服务的异步初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆