【问题标题】:Angular 6: Observable HTTPClientAngular 6:可观察的 HTTPClient
【发布时间】:2018-12-29 10:24:44
【问题描述】:

我有一个现有的 Angular 2 项目,已移植到 Angular 6,现在我的 HTTP-observable 不再运行。据我所知,它是关于新可观察对象的不同操作。

我的服务返回一个 observable。我在组件中订阅并设置间隔和 startindex。

如何在 Angular 6 中做到这一点?

// SERVICE 
@Injectable ()
export class ViewService
{
  constructor (private http : HttpClient)
  {      }

  foo () : Observable <any>
  {
    return this.http.get ("http://blabla",
      {responseType: "json"});
  }
}



// COMPONENT
export class ViewComponent
{
  constructor (private vs : ViewService)
  {      }

  ngOnInit ()
  {
    this.vs.foo ().interval (1000).startWith (0).subscribe (
      (resp) =>
      {
      });
  }
}

错误

错误:错误 TS2339:类型上不存在属性“间隔” '可观察'

使用 rxjs 6.0.0

【问题讨论】:

标签: angular


【解决方案1】:

Angular6 采用了 RxJS v6 中的一些重大更改,您需要注意:

  1. 可观察对象和操作符的导入语句的不同方式。所以你需要在组件控制器的顶部以这种方式添加操作符:

    import { interval } from 'rxjs';
    import { startWith, mergeMap } from 'rxjs/operators';
    
  2. 使用 pipe() 作为链接运算符的方法,链接它们的旧方法将不起作用:

    // COMPONENT
    export class ViewComponent
    {
        constructor (private vs : ViewService) {}
    
        ngOnInit () {
           const obs$ = interval(1000).pipe( // This is your main observer chain
               startWith(0),
               mergeMap(res => this.vs.foo()) // This will start a sub-chain of observer that is isolated to your main chain
                  .subscribe(res => console.log('subscription of the sub-chain: ', res))
           )
    
           obs$.subscribe(res => console.log('subscription of main chain: ', res));
        }
     }
    

如果您仍然感到困惑,请观看 Ben Lesh 的视频,了解 RxJS v6 中的变化:https://www.youtube.com/watch?v=JCXZhe6KsxQ

【讨论】:

    【解决方案2】:

    首先你必须从rxjs 导入interval

    import { interval } from 'rxjs';
    

    导入startWith,您还必须从rxjs/operators 导入mergeMap

    import { startWith, mergeMap } from 'rxjs/operators';
    

    然后你可以像这样使用它们:

    interval(1000).pipe(
      startWith(0),
      mergeMap(iRes => this.vs.foo())).subscribe(resp => {
        console.log(resp);
      });
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-25
      • 2018-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多