![](/img/trans.png)
[英]How to know the request progress in each http request in Ionic and Angular
[英]Firebase, Typescript, request progress : how to display a request progress?
我在Angular項目中與Angular Material一起使用angularfire2
。
我認為最好讓用戶知道請求正在處理中。
不使用Firebase,我知道我可以使用Interceptors
來處理這種事情。 但是使用Firebase,它們不再起作用。
因此,我決定提供一種服務,該服務將進行所有HTTP調用,並使它的行為像攔截器一樣。
我的問題是,當您創建請求時,創建的Observable永遠不會結束。 這意味着我可以顯示進度狀態,但從不隱藏它。
例如,我有此方法,它返回集合的每個文檔:
getCollection<T>(collection: string, query?: QueryFn): Observable<T[]> {
return (query ? this.db.collection<T>(collection, query) : this.db.collection<T>(collection)).valueChanges();
}
當應用程序獲取集合時,如何顯示進度條?
我通常會經過這樣的事情
getCollection<T>(collection: string, query?: QueryFn): Observable<T[]> {
this.loading = true;
return (query ? this.db.collection<T>(collection, query) : this.db.collection<T>(collection)).pipe(finalize(() => this.loading = false));
}
但是valueChanges
可以防止這種情況。
如果您的可觀察物永遠無法完成,則可以使用輕按運算符。 當您的流發出沒有副作用的新值時,可使用此運算符執行操作:
getCollection<T>(collection: string, query?: QueryFn): Observable<T[]> {
this.loading = true;
return (query ? this.db.collection<T>(collection, query) : this.db.collection<T>(collection)).pipe(tap(() => this.loading = false));
}
編輯:如果您想模仿標准的API行為。 您可以使用.take
運算符。
例如:
getCollection<T>(collection: string, query?: QueryFn): Observable<T[]> {
this.loading = true;
return this.db.collection<T>(collection, query)
.pipe(
take(1),
finalize(() => this.loading = false)
);
}
使用此take
操作符,您的觀測值將在首次數據發射后完成。 但是正如我在評論中所說,它打破了fireStore
的概念,因為如果您向集合添加另一個項目,則需要再次調用getCollection
以獲得新的Observable
。
順便說一句:看來您的三元數是沒有用的(但是我真的不了解firebase)。 變更:
return (query ? this.db.collection<T>(collection, query) : this.db.collection<T>(collection)).pipe(tap(() => this.loading = false));
至
return this.db.collection<T>(collection, query).pipe(tap(() => this.loading = false));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.