【发布时间】:2023-03-22 02:36:02
【问题描述】:
我有一个http interceptor,它会在请求开始和结束时发出一个“字符串”:
@Injectable({
providedIn: 'root'
})
export class LoadingIndicatorService implements HttpInterceptor {
private loadingIndicatorSource = new Subject<string>();
private loadingIndicator$ = this.loadingIndicatorSource.asObservable();
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.updateVisibility('block');
return next.handle(req)
.pipe(
finalize(
() => {
this.updateVisibility('none');
}
)
)
;
}
updateVisibility(state: string) {
this.loadingIndicatorSource.next(state);
}
getLoadingIndicator() {
return this.loadingIndicator$;
}
}
这是我注入服务的组件:
export class AppComponent {
display = 'none';
constructor(public authenticationService: AuthenticationService,
public loadingIndicatorService: LoadingIndicatorService) {
this.loadingIndicatorService.getLoadingIndicator().subscribe(visibility => {
console.log(visibility);
this.display = visibility;
});
}
}
实际上我正在尝试显示加载指示器:
<div [style.display]="display">
<mat-progress-bar mode="indeterminate" color="warn" ></mat-progress-bar>
</div>
我从 Angular 官方网站流出 this 教程。
但是订阅方法永远不会执行。
为什么订阅方法不起作用?
【问题讨论】:
-
浏览器说:“TypeError:this.loadingIndicator$.next 不是函数”。这是我的进口:
import {Observable, Subject} from 'rxjs'; -
您的代码是
this.loadingIndicatorSource.next(state),但您的错误是this.loadingIndicator$.next。请贴出错误代码。 -
抱歉,还有一条评论,但它已删除,我的评论仍然保留。有人说使用“
this.loadingIndicator$.next(state)”,然后他删除了评论。 -
我会将
this.loadingIndicatorService.getLoadingIndicator()存储在一个变量中并订阅该变量。看起来会好很多。 -
它不会被触发,因为拦截器需要使用 HTTP 请求。由于您没有创建,因此永远不会调用
next方法,这意味着您不会运行订阅。
标签: javascript angular typescript observable reactivex