【发布时间】:2020-04-27 21:56:03
【问题描述】:
我正在使用 Angular 8 做一个 Web 应用程序,我想在执行 HTTP 请求时显示一个加载微调器。
我的实现没有显示加载微调器,我找不到原因。
服务
@Injectable()
export class UserService {
// Caching
private bsResource: BehaviorSubject<string[]> = new BehaviorSubject([]);
private readonly resources$: Observable<string[]> = this.bsResource.asObservable();
constructor(
private http: HttpClient
) {
}
// Calling this method the loading spinner is not showing.
getResources(): Observable<string[]> {
if (this.bsResource.getValue().length === 0) {
this.fetchResourceList().toPromise().then(res => this.bsResource.next(res));
}
return this.resources$;
}
// The loading spinner appears if I use this method directly and make this method public.
private fetchResourceList(): Observable<string[]> {
return this.http.get<string[]>('MY_URL');
}
}
组件:
@Component({
templateUrl: './create-new.component.html',
styleUrls: ['./create-new.component.scss']
})
export class CreateNewComponent {
resourceList$: Observable<string[]> = this.service.getResources();
constructor(
private service: UserService
) { }
}
模板
<div class="form-group">
<label for="resourceSelect">* Resources</label>
<div *ngIf="resourceList$ | async as resourceList; else loading">
<ng-container *ngIf="resourceList.length; else noResults" >
<div *ngFor="let r of resourceList; index as i">
<!-- Show the result using checkboxes -->
</div>
</ng-container>
</div>
</div>
<ng-template #loading>
<br/>
<div class="spinner-border spinner-border-sm text-muted" role="status">
<span class="sr-only">Loading...</span>
</div>
</ng-template>
<ng-template #noResults>
<div class="text-muted">No results.</div>
</ng-template>
我不明白为什么使用this.service.getResources() 加载微调器没有显示,如果我使用this.service.fetchResourceList() 加载微调器显示正确。
我的目标是使用我提供的示例正确显示加载微调器,并保留我在组件中调用的方法。
【问题讨论】:
-
这么简单的调用你的代码看起来太复杂了……你在发布之前清理了代码,还是完整的代码?
-
@Random 嗨,我删除了很多对我的问题不重要的东西。我在发布之前已经清理了它,这就是我今天使用的确切代码。它看起来很大,因为我正在实现本地缓存以将信息保存在内存中以避免将来不必要的 HTTP 请求。至少我是这么看的。
-
您在控制台中看到任何错误吗?能否也确认一下http调用是否成功?
-
@KarthickManoharan 嗨,控制台中没有错误,我可以确认 HTTP 调用正确。请求的信息/结果正在显示,但加载微调器没有。
-
感谢您的确认。您是否还可以通过限制速度来延迟响应时间来确保?因为如果 API 响应速度很快,那么微调器可能不会显示
标签: angular