代码之家  ›  专栏  ›  技术社区  ›  Stephane

“rxjs/operators”和“rxjs/add/operator/”有什么区别?

  •  2
  • Stephane  · 技术社区  · 6 年前

    两者有什么区别 import { map } from 'rxjs/operators'; import 'rxjs/add/operator/map'; ?

    我在服务方法中使用它进行登录:

    // import { map } from 'rxjs/operators'; // Fails at runtime
    import 'rxjs/add/operator/map'; // Works fine at runtime
    
      public login(username: string, password: string): Observable<any> {
        console.log('Sending the login credentials to obtain a token');
        const credentials = { 'email': username, 'password': password };
        return this.httpService.postWithHeadersInResponse(URI_LOGIN, credentials)
          .map((response: HttpResponse<any>) => {
            const header = response.headers.get(this.authService.getHeaderName());
            const token = this.authService.extractTokenFromHeader(header);
            console.log('The token from the response header: ' + token);
            this.authService.setJwtTokenToLocalStorage(token);
          });
      }
    
    2 回复  |  直到 6 年前
        1
  •  3
  •   iofjuupasli    6 年前

    区别在于当你使用 rxjs/add/operator/map 它改变了Observable的原型,所以你可以 . (点)运算符:

    this.httpService.postWithHeadersInResponse(URI_LOGIN, credentials)
      .map(...);
    

    但这种使用运算符的方式已被弃用。当前方式 rxjs/operators :

    import { map } from 'rxjs/operators';
    this.httpService.postWithHeadersInResponse(URI_LOGIN, credentials)
      .pipe(map(...));
    
        2
  •  1
  •   Develobba    6 年前

    RXJS更改了公共的_API.ts,并在更新的版本中移动了RXJS项目中的一些文件(我猜是5.5+版本)。

    现在正确的方法是:

    import { map } from 'rxjs/operators'
    

    另一种方法将在较新版本中被弃用/删除(我在博客的某个地方阅读了7.0)。另外,另一种方法只在较新的RXJS版本中与RXJS兼容。

    RXJS Compat将不再与RXJS 7.0一起工作(很可能)