【问题标题】:Angular RxJS, replay HTTP requestAngular RxJS,重放 HTTP 请求
【发布时间】:2020-05-03 14:07:32
【问题描述】:

我正在寻找一种方法来按需重播我的 http/get 请求,例如在发布从服务器更新我的数据之后。我正在查看重复或扩展运算符,但不确定这是正确的路径。推荐的模式是什么?

const url = 'https://jsonplaceholder.typicode.com/todos/';
const data$ = this.http.get<Todo[]>(url);
data$.subscribe(console.log);
// wait 5 sec for instance, then replay the http get again and get data$ updated

谢谢!

【问题讨论】:

    标签: angular http rxjs


    【解决方案1】:

    您可以使用 timer 每 5 秒发出一个事件,然后使用像 switchMap 这样的高阶映射来请求数据。

    const url = 'https://jsonplaceholder.typicode.com/todos/';
    const data$ = this.http.get<Todo[]>(url);
    const dataWithTimer$ = timer(0, 5000).pipe(switchMap(() => data$))
    dataWithTimer$.subscribe(console.log);
    

    【讨论】:

      【解决方案2】:

      感谢Yasser的回答,我终于去:

      const url = 'https://jsonplaceholder.typicode.com/todos/';
      const webData$ = this.http.get<Todo[]>(url);
      const force$ = new BehaviorSubject<boolean>(true);
      const forcedData$ = force$.pipe(switchMap((b) => webData$));
      forcedData$.subscribe(console.log);
      setTimeout(() => force$.next(true), 5000);
      

      我可以手动使用强制更新

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-26
        • 1970-01-01
        • 2018-11-24
        • 2021-12-08
        • 1970-01-01
        • 1970-01-01
        • 2019-12-25
        相关资源
        最近更新 更多