简体   繁体   English

如何制作依赖于 2 个 http 调用完成的 canActivate 防护?

[英]How do I make a canActivate guard that depends on 2 http calls finishing?

I have 2 http calls, where the second depends on the first.我有 2 个 http 调用,其中第二个取决于第一个。 How do I approach making a canActivate guard that waits for the two http calls to finish before returning true, and if it takes "too long", say 5 seconds, it returns false.我如何制作一个 canActivate 守卫,在返回 true 之前等待两个 http 调用完成,如果它花费“太长时间”,比如 5 秒,它返回 false。 In searching around it seems maybe rxjs.timeout could work but I'm not getting how to wire that up in the context of the 2 http calls.在四处搜索时,似乎 rxjs.timeout 可以工作,但我不知道如何在 2 个 http 调用的上下文中连接它。

My current guardless code is like this.我目前的无守卫代码是这样的。 I'm expecting(?) that the guard would eliminate the code in the component ngOnInit().我期待(?)守卫会消除组件 ngOnInit() 中的代码。

export class ApiQueryService {
  constructor(private http: HttpClient) { }

  getFirstObj$(name: string): Observable<any> {
    return this.http.get(environment.apiUrl + '?name=' + name);
  }

  // "link" parameter comes from the getFirstObj$ call
  getSecondObj$(link: string): Observable<any> {
    return this.http.get(link);
  }
}

export class InitService {
  constructor(private  apiQueryService: ApiQueryService) {
  }

  init(name: string) {
    this.apiQueryService.getFirstObj$(name)
      .subscribe(firstObj => {
      this.apiQueryService.getSecondObj$(firstObj.link))
          .subscribe(secondObj => {
            console.log('secondObj:', secondObj);
          });
      });
  }
}

export class MyComponent implements OnInit {
  ngOnInit() {
    this.initService.init('myName');
  }
}

You can indeed use timeout, and switchMap to chain the two calls.您确实可以使用 timeout 和 switchMap 来链接两个调用。

return this.apiQueryService.getFirstObj$(name).pipe(
  switchMap(firstObj => this.apiQueryService.getSecondObj$(firstObj.link)),
  map(secondObj => true),
  timeout(5000),
  catchError(() => of(false))
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM