Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

javascript - RxJS zip和管道组合无法使用(RxJS zip and pipe in combination not working)

I have two server calls that I need to wait for.

(我有两个服务器呼叫需要等待。)

However, the user can decide if the second server call is even made.

(但是,用户可以决定是否进行第二次服务器调用。)

All of this is happening in an Angular Resolver, as the data is necessary for the next page.

(所有这些都是在Angular Resolver中发生的,因为数据对于下一页是必需的。)

The problem is that from my zip function the code never reaches the pipe, leaving me stuck in the resolver.

(问题是从我的zip函数中,代码永远不会到达管道,从而使我陷于解析器中。)

Here is the procedure:

(步骤如下:)

  1. zip my requests

    (压缩我的要求)

  2. pipe them

    (用管道)

  3. and return an observable to my resolve function

    (并向我的resolve函数返回一个可观察的)

this is my code:

(这是我的代码:)

public resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
    Observable<any> | Promise<any> { //

    const id = +route.paramMap.get('id');
    const wantsSecondRequest = +route.paramMap.get('wantsSecondRequest');


    const requests: Array<Observable<any>> = new Array();

    requests.push(firstServerCallHappensHere());
    if (wantsSecondRequest === 1) {
      requests.push(secondServerCallHappensHere());
    }

    return zip(requests).pipe(take(1), mergeMap(([a, b]) => {
         // DO STUFF WITH MY REQUESTS
          return of(a);
    }));

}

(})

I tried it with Promise.all and working with Promises instead of Observables, but the issue with those are that I am unable to never complete the Promises in the case of an error, so that the navigation never happens.

(我使用Promise.all进行了尝试,并使用Promises而不是Observables,但是这些问题是,在发生错误的情况下,我永远无法完成Promises,因此导航永远不会发生。)

  ask by Roundtrip translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

According to the doc http://reactivex.io/documentation/operators/zip.html zip() accepts a number of parameters which are observables but you provide an array.

(根据文档, http: zip()接受许多可观察到的参数,但您提供了一个数组。)

It might help:

(它可能会有所帮助:)

public resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
    Observable<any> | Promise<any> { //

    const id = +route.paramMap.get('id');
    const wantsSecondRequest = +route.paramMap.get('wantsSecondRequest');

    return zip(
      firstServerCallHappensHere(),
      wantsSecondRequest === 1 ? secondServerCallHappensHere() : undefined,
    ).pipe(take(1), mergeMap(([a, b]) => {
         // DO STUFF WITH MY REQUESTS
          return of(a);
    }));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...