我想在请求尝试命中时打开一个加载器弹出窗口,在得到响应后,我想关闭它。 有没有办法使用httpclient从一个地方执行它。
答案 0 :(得分:1)
这样的事情:
@Injectable()
export class I1 implements HttpInterceptor {
constructor(public service: SomeService) {
console.log(service);
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
setTimeout(() => {
this.service.loading = true;
});
return next.handle(req).do(
(event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
setTimeout(() => {
this.service.loading = false;
});
}
},
(err: any) => {
}
);
}
}
<强> SomeService.ts 强>:
@Injectable()
export class SomeService {
_loading = false;
constructor() {
}
set loading(isLoad: boolean) {
this._loading = isLoad;
}
get loading() {
return this._loading;
}
}
在您的Root
组件中注入此服务:
@Component({
selector: 'my-app',
template: `
IsLoading: {{service.loading}}
<div><h3>Response</h3>{{response|async|json}}</div>
<button (click)="request()">Make request</button>`
,
})
export class AppComponent {
response: Observable<any>;
constructor(private http: HttpClient, public service: SomeService) {}
request() {
const url = 'https://jsonplaceholder.typicode.com/posts/1';
this.response = this.http.get(url, {observe: 'body'});
}
}
SpinnerService:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
import { share } from 'rxjs/operators';
@Injectable()
export class SpinnerService {
private visible$ = new BehaviorSubject<boolean>(false);
show() {
this.visible$.next(true);
}
hide() {
this.visible$.next(false);
}
isVisible(): Observable<boolean> {
return this.visible$.asObservable().pipe(share());
}
}