Property 'do' does not exist on type 'Observable'

后端 未结 5 1414
遇见更好的自我
遇见更好的自我 2021-02-01 02:04

After upgrading to Angular 6.0 and Rxjs to 6.0 I receive the following compilation error:

Property \'do\' does not exist on type \'Observable\'.

Her

5条回答
  •  耶瑟儿~
    2021-02-01 02:27

    I appreciate Tjaart van der Walt's response about how to resolve the "breaking changes" introduced in Angular/rxjs7++. But I still encountered several problems trying to apply his response to my Angular interceptor:

    Here is the updated code (the sections that failed to compile are marked "OLD")

    import {Injectable} from '@angular/core';
    import {HttpEvent, HttpInterceptor, HttpResponse} from '@angular/common/http';
    import {HttpHandler, HttpRequest, HttpErrorResponse} from '@angular/common/http';
    
    /*
      OLD:
      import {Observable} from 'rxjs/Observable';
      import 'rxjs/add/operator/do';
     */
    import { Observable } from 'rxjs';
    import { of } from 'rxjs';
    import { tap, catchError } from 'rxjs/operators';
    
    import { AuthService } from './auth.service';
    
    @Injectable()
    export class StockAppInterceptor implements HttpInterceptor {
    
      constructor(private authService: AuthService) {}
    
      intercept(req: HttpRequest, next: HttpHandler): Observable> {
        if (this.authService.authToken) {
          const authReq = req.clone({
            headers: req.headers.set(
              'Authorization',
              this.authService.authToken
            )
          });
          console.log('Making an authorized request');
          req = authReq;
        }
        /*
         * OLD:
         * return next.handle(req)
         *   .do(event => this.handleResponse(req, event),
         *      error => this.handleError(req, error));
         */
        return next.handle(req).pipe(
          tap(
            event => this.handleResponse(req, event),
            error => this.handleError(req, error)
          )
        );
      }
    
    
      handleResponse(req: HttpRequest, event) {
        console.log('Handling response for ', req.url, event);
        if (event instanceof HttpResponse) {
          console.log('Request for ', req.url,
              ' Response Status ', event.status,
              ' With body ', event.body);
        }
      }
    
      handleError(req: HttpRequest, event) {
        console.error('Request for ', req.url,
              ' Response Status ', event.status,
              ' With error ', event.error);
      }
    }
    

    Required changes include changing import paths, and substituting pipe(), tap() and of().

    This link is also a good resource for RxJS6 changes:

    https://www.academind.com/learn/javascript/rxjs-6-what-changed/

提交回复
热议问题