在Angular 2中的Observable中获取数据后的队列/回调函数 [英] Queue/callback function after fetching data in an Observable in Angular 2

查看:308
本文介绍了在Angular 2中的Observable中获取数据后的队列/回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从服务中获取数据后排队或创建一个回调函数,但是该函数似乎被异步调用.我希望在提取数据之后调用该函数,因为该函数需要Observable中的数据.到目前为止,由于在将所有数据分配给this.items之前调用了该函数,因此无法正常工作.

I am trying to queue or create a callback function after fetching data from service, but the function seems to be called asynchronously. I'd like the function to be called after the data is fetched as the data in the Observable is required for the function. So far this doesn't work as the function is called before all the data has been assigned to this.items:

this._itemsService.getItems().subscribe(items => this.items = items, err => {}, callThisFunctionAfter());

有没有一种方法可以将函数转换为回调或像promise那样排队呢?

Is there a way to turn the function into a callback or queue it like a promise?

推荐答案

您需要将其设置为闭包而不是函数调用.

You need to make it a closure not a function call.

this._itemsService.getItems().subscribe(items => this.items = items, err => {}, () => callThisFunctionAfter());

在没有() =>的情况下调用该函数,并将结果作为回调传递.

Without () => the function is called and the result is passed as callback.

这是callThisFunctionAfter()subscribe()之前执行的原因,而不是在观察者关闭时执行的原因.

This is the reason callThisFunctionAfter() is executed before subscribe() instead of when the observable was closed.

这篇关于在Angular 2中的Observable中获取数据后的队列/回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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