【问题标题】:I dont get rxjs 6 with angular 6 with interval, switchMap, and map我没有得到 rxjs 6 和 angular 6 的间隔、switchMap 和 map
【发布时间】:2018-10-16 11:19:49
【问题描述】:

我想将我的 rxjs 代码更新为 6,但我不明白。

在我没有每 5 秒轮询一次新数据之前:

import { Observable, interval } from 'rxjs';
import { switchMap, map } from 'rxjs/operators';

var result = interval(5000).switchMap(() => this._authHttp.get(url)).map(res => res.json().results);

现在...当然,它坏了,文档让我无处可去。

如何编写以上内容以符合 rxjs 6?

谢谢

【问题讨论】:

  • 坏了怎么办?您所做的只是因为您直接从 rxjs 导入,这是错误的,并且导入所有“原型”运算符,如果您以后从 import { switchMap, map } from 'rxjs/operators'; 导入,这不是您想要的

标签: angular rxjs rxjs6


【解决方案1】:

代码应如下所示。您需要使用pipe 运算符。

import { interval } from 'rxjs';
import { switchMap, map } from 'rxjs/operators';

const result = interval(5000).pipe(
switchMap(() => this._authHttp.get(url)),    
map(res => res.results)
)

【讨论】:

  • 以下是使用您的建议时出现的错误:[ts] Property 'pipe' does not exist on type 'OperatorFunction'。
  • 确保在导入列表中添加管道:import { Observable, interval, pipe } from 'rxjs';
  • 我认为 this._authHttp.get(url).pipe 而不是 this._authHttp.get(url) ).pipe 。这个 git 摆脱了错误
  • 但现在我得到 [ts] 属性 'json' 在类型 '{}' 上不存在。对于 res.json()
  • 新的 HttpClient 只返回数据,没有响应(除非你在选项中设置了 observe: 'response')。所以你可以删除 .json()
【解决方案2】:

经过大量研究,我可以从 RxJs 的 6 和 Angular 6 中提出以下更新方法

搜索 API 在每 5 秒的间隔后被调用,并且在计数 > 5 后取消订阅:

let inter=interval(5000)

let model : ModelComponent;
model=new ModelComponent();
model.emailAddress="mdshahabaz.khan@gmail.com";


let count=1;
this.subscriber=inter.pipe(
          startWith(0),
          switchMap(()=>this.asyncService.makeRequest('search',model))
        ).subscribe(response => {
          console.log("polling")
          console.log(response.list)
          count+=1;
          if(count > 5){
            this.subscriber.unsubscribe();
          }
        });

API 请求:

   makeRequest(method, body) : Observable<any> {
    const url = this.baseurl + "/" + method;

    const headers = new Headers();
    this.token="Bearer"+" "+localStorage.getItem('token'); 
    headers.append('Authorization', this.token);
    headers.append('Content-Type','application/json');

    const options = new RequestOptions({headers: headers});
    return this.http.post(url, body, options).pipe(
        map((response : Response) => {
            var json = response.json();                

           return json; 
        })
    );
}

不要忘记取消订阅以避免内存泄漏。

ngOnDestroy(): void {
if(this.subscriber){
  this.subscriber.unsubscribe();
}

}

【讨论】:

    猜你喜欢
    • 2018-10-21
    • 2018-11-08
    • 2019-02-08
    • 2018-12-19
    • 2018-10-15
    • 2020-01-10
    • 2018-10-17
    • 1970-01-01
    相关资源
    最近更新 更多