typescript – 角度2服务的异步初始化
发布时间:2020-12-17 07:37:46 所属栏目:安全 来源:网络整理
导读:我有一个Angular 2服务,需要在启动异步工作时进行异步工作,并且在初始化完成之前不应该使用它. @Injectable()export class Api { private user; private storage; constructor(private http: Http) { this.storage = LocalStorage; this.storage.get('user')
我有一个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没有初始化,因此发送错误的请求. 生命周期挂钩(OnInit,OnActivate等)不适用于服务,仅适用于组件和指令,因此我无法使用它们. 从get()调用中存储Promise将需要依赖于用户的所有不同方法等待它,从而导致大量的代码复制. 在Angular 2中进行异步初始化服务的推荐方法是什么?
您可以利用一个observable来使用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() { // 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(...); }); } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |