我在我的角度應用程式中有許多 api 呼叫,如果資料來自服務器,我想在其中顯示加載組件。
為此,我有一個這樣的加載器服務:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class LoaderService {
isLoading = new Subject<boolean>();
show() {
this.isLoading.next(true);
}
hide() {
this.isLoading.next(false);
}
}
我也有一個httpInterceptor,我使用這樣的showandhide方法:
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
this.loaderService.show();
return new Observable((observer) => {
next.handle(request).subscribe(
(res) => {
observer.next(res);
},
(err: HttpErrorResponse) => {
this.loaderService.hide();
if (err.error.message) {
this.customNotificationService.showNotification(
err.error.message,
3000,
'error'
);
} else {
this.customNotificationService.showNotification(
'Ismeretlen eredet? hiba. Lépj kapcsolatba a rendszer üzemeltet?jével.',
3000,
'error'
);
}
},
() => {
this.loaderService.hide();
}
);
});
}
在我想使用加載組件的組件中,我在模板中有這個:
<loading-overlay
[visible]="loadingOverlayVisible | async"
loadingText=""
></loading-overlay>
在 ts 中:
loadingOverlayVisible: Subject<boolean> = this.loaderService.isLoading;
除了一種情況外,這有效:ngOnInit. 當組件加載時,我會像這樣加載初始資料:
ngOnInit() {
this.gridData = { data: [], total: 0 };
this.userService.getUsers().subscribe((users) => {
users.forEach((user) => {
// we get this as string from the backend
user.lastLoginDateDisplay = new Date(user.lastLoginDateDisplay!);
});
this.gridData = { data: users, total: users.length };
});
}
資料被加載,但沒有任何加載指示器。如果我改變邏輯并使用標準subscribe/unsubscribe方式,它就可以作業。但是使用異步管道會更清潔/更智能。
所以,問題是:如何做到這一點?
uj5u.com熱心網友回復:
LoaderService.isLoading 應該是一個 BehaviorSubject。我不確定,但我認為 ngInit 在模板首次評估之前完成。如果我是對的,那么 LoaderService.isLoading 已經發出 true,當您的異步管道訂閱時,為時已晚。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/437356.html
