Angular 6 RXJS Import Syntax?

后端 未结 5 1468
北恋
北恋 2020-12-08 09:24

I\'m migrating an Angular 5 app to the latest CLI and Angular 6 RC and all of my Observable imports are broken. I see that Angular 6 changes the way the imports work, but I

相关标签:
5条回答
  • 2020-12-08 09:58

    Run these 2 commands after running ng update. This should fix the rxjs imports:

    1. npm i -g rxjs-tslint
    2. rxjs-5-to-6-migrate -p src/tsconfig.app.json

    References:

    • https://github.com/ReactiveX/rxjs-tslint
    0 讨论(0)
  • 2020-12-08 10:06

    Pipes are what is required for operator(s) going forward.

    version: rxjs 6.0.1

    Example:

    import { Observable } from "rxjs";
    import { map } from "rxjs/operators";
    
    Observable.create((observer: any) => {
        observer.next('Hello')
    }).pipe(map((val: any) => val.toUpperCase()))
      .subscribe((x: any) => addItem(x))
    
    
    function addItem(val: any) {
        console.log('val', val);
    }
    
    //output - (In uppercase)
    HELLO
    
    0 讨论(0)
  • 2020-12-08 10:12

    You just need to import like operators

    import { Observable } from 'rxjs';
    import { map, catchError, timeout } from 'rxjs/operators';
    
    0 讨论(0)
  • 2020-12-08 10:13

    From rxjs 5.5, catch has been renamed to catchError function to avoid name clash.

    Due to having operators available independent of an Observable, operator names cannot conflict with JavaScript keyword restrictions. Therefore the names of the pipeable version of some operators have changed.

    import { catchError } from 'rxjs/operators';
    

    For throw you can use ErrorObservable.

    import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
    ErrorObservable.create(new Error("oops"));
    

    rxjs 6

    Instead of ErrorObservable use throwError.

     import { throwError } from 'rxjs'
     throwError(new Error("oops"));
    

    Also you will now have to pipe the operators instead of directly chaining them to the observable

    0 讨论(0)
  • 2020-12-08 10:20

    Or if you want to keep using version 6.0.0 you do

    npm i --save rxjs-compat

    to add reverse compatibility

    0 讨论(0)
提交回复
热议问题