Scenario: In the daily development process, for one reason or another, the network request may not be completed when the route is switched, which can cause some bad effects
solution
-
Determine the time to switch routes
-
When the route switchover is complete, cancel all pending requests
Implementation steps
-
Ng g s service/cancel-http –skip-tests
// cancel-http.service.ts @Injectable({ providedIn: 'root' }) export class CancelHttpService { public cancelPenddingRequest$ = new Subject<void>(); constructor() { } public cancelPendingRequests(): void { this.cancelPenddingRequest$.next(); } public onCancelPendingRequests(): Observable<void> { return this.cancelPenddingRequest$.asObservable(); }}Copy the code
-
Ng g interceptor Cancel-request
// cancel-request.interceptor.ts export class HttpCancelInterceptor implements HttpInterceptor { constructor(private cancelHttpService: CancelHttpService) { } intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> { return next.handle(request).pipe(tap(evt => console.log(evt)), takeUntil(this.cancelHttpService.onCancelPendingRequests())) } } ``` Copy the code
-
The root component listens for routing events to determine when to cancel the switch request
// app.component.ts @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { constructor(private router: Router, private cancelService: CancelHttpService) { this.router.events.subscribe(event => { if (event instanceof ActivationEnd) { this.cancelService.cancelPendingRequests() } }) } } Copy the code