Angular - Convert a Observable<number> to a number

本秂侑毒 提交于 2019-12-01 06:40:17

问题


I'm using ngrx store to record state, my state currently holds my list of accounts and the current page (for paging).

On my list of accounts component i call the store to get the current page and pass that to a service (web api) to get the list of accounts.

this.currentPage$ = this.store.select(getCurrentPage);

My angular service is expecting a variable (currentPage) but as a type of number, the store select returns an Observable.

getListOfCustomer(currentPage: number): Observable<ListDto<CustomerList>> {}

My variable this.currentPage$ is currently a type of Observable<number>

How can i convert an Observable<number> to a number to pass it to my service?


回答1:


subscribe to get result as number:

currentPageSub :Subscription;
...
this.currentPageSub = this.store.select(getCurrentPage).subscribe(
 (page: number) => {
     this.currentPage$=page;
 }
);



回答2:


You can create an async function and convert the observable to a promise and await it

async method(){
    var pageNr = await this.currentPage$.toPromise();
    this.getListOfCustomer(pageNr);
}


来源:https://stackoverflow.com/questions/47013653/angular-convert-a-observablenumber-to-a-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!