appp.module.ts
import { AppComponent} from './app.component';
import { ManageActionsComponent } from './components/match'
import { NgModule} from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { UICInterceptor } from './modules/shared/services/inerceptor/UICInterceptor';
import { NgSelectModule } from '@ng-select/ng-select';
import { BrowserAnimationsModule } from @angular/platform-browser/animations';
import { ErrorInterceptor } from './modules/shared/services/inerceptor/error-interceptor';
@NgModule({
declarations: [
AppComponent,
ManageActionsComponent,
],
imports: [
AppRoutingModule,
NgSelectModule,
BrowserAnimationsModule,
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: UICInterceptor,
multi: true,
},
{
provide: HTTP_INTERCEPTORS,
useClass: ErrorInterceptor,
multi: true,
}
],
bootstrap: [AppComponent],
})
export class AppModule {}
manageActions.component.ts
errorMessage: string = '';
constructor (
private readonly api: HttpCallsService,
private errorInterceptor: ErrorInterceptor
){}
ngOnInit(): void {
this.errorInterceptor.errorMessage$.subscribe(errorMessage=>{
console.log('errorMessage in component', errorMessage);
this.errorMessage = errorMessage;
});
this.retriveActions();
error-interceptor.ts
import BehaviorSubject, Observable, Subject, throwError) from 'rxjs';
import { retry, catchError, finalize} from 'rxjs/operators';
import Injectable } from '@angular/core';
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpErrorResponse,
@Injectable({
providedIn: 'root',
export class ErrorInterceptor implements HttpInterceptor {
constructor() {}
private errorMessage = new BehaviorSubject<string>('asdfsd');
errorMessage$ = this.errorMessage.asObservable();
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
): Observable<HttpEvent<unknown>> {
return next.handle (request).pipe(
catchError((error: HttpErrorResponse) => {
let errorMessage = ¹¹;
if (error.error instanceof ErrorEvent) {
// client-side error
errorMessage = "Error: $[error.error.message}`;
} else {
// server-side error
errorMessage = Error Code: $[error.status}\nMessage: ${error.message}`;
console.log('This is the value', errorMessage)
}
this.errorMessage.next(errorMessage);
return throwError(()->errorMessage);
}),
finalize(()=> {})
);
}
}
我正在尝试订阅 manageActionComponent 并在 html 文件中显示 'errorMessage' 属性的任何更新,但可观察对象只采用拦截器文件中分配的第一个值,在本例中为 '' 空字符串,然后它不会再更新了
我尝试将订阅设置为 takeUntil(NEVER) 但这也不起作用。我已经尝试将 setTimeout() 设置为 100,但也没有用。
我做错了什么吗?请让我知道,这是我第一次使用拦截器,所以我可能做错了。