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

是否有人使用过RXJS在HTTP中所做的妥协和承诺?

  •  2
  • Indraraj26  · 技术社区  · 7 年前

    有人用过吗? toPromise Promise.all 从HTTP中的RXJS?请给我举个例子。
    如何检查组件中的两个请求是否成功 promise.all 返回一些消息,比如api是否成功?

    getPostAsync() {
        return this.http.get('https://jsonplaceholder.typicode.com/posts')
                        .pipe(map((res:Response) => { return res.json();}))
                        .pipe(catchError((error) => { return throwError(error);}))
    }
    
    getPostAsync1() {
        return this.http.get('https://jsonplaceholder.typicode.com/posts/1')
                        .pipe(map((res:Response) => { return res.json();}))
                        .pipe(catchError((error) => { return throwError(error);}))
    }
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   Dzhavat Ushev    7 年前

    我不会用 toPromise 也不 Promise.all 处理请求时。最好用观察和运算符来处理。我写了一篇文章 article about replacing Promises with RxJS . 而不是 承诺所有 我会用 forkJoin 监听两个或多个请求的完成。

        2
  •  0
  •   Konstantin Sof    7 年前

    可以对多个请求使用combinelatest https://www.learnrxjs.io/operators/combination/combinelatest.html

    combineLatest(this.http.get('/api'), this.http.get('/api2'))
    .subscribe((res: any) => {
        const res = res[0];
        const res2 = res[1];
    });
    
    推荐文章