如何制作依赖于 2 个 http 调用完成的 canActivate 守卫?
How do I make a canActivate guard that depends on 2 http calls finishing?
我有 2 个 http 调用,其中第二个依赖于第一个。我如何制作一个 canActivate 守卫,它在返回 true 之前等待两个 http 调用完成,如果需要 "too long",比如 5 秒,它 returns false。在四处搜索时,似乎 rxjs.timeout 可以工作,但我不知道如何在 2 个 http 调用的上下文中连接它。
我现在的无守卫代码是这样的。我期待(?)守卫会消除组件 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');
}
}
你确实可以使用 timeout 和 switchMap 来链接这两个调用。
return this.apiQueryService.getFirstObj$(name).pipe(
switchMap(firstObj => this.apiQueryService.getSecondObj$(firstObj.link)),
map(secondObj => true),
timeout(5000),
catchError(() => of(false))
);
我有 2 个 http 调用,其中第二个依赖于第一个。我如何制作一个 canActivate 守卫,它在返回 true 之前等待两个 http 调用完成,如果需要 "too long",比如 5 秒,它 returns false。在四处搜索时,似乎 rxjs.timeout 可以工作,但我不知道如何在 2 个 http 调用的上下文中连接它。
我现在的无守卫代码是这样的。我期待(?)守卫会消除组件 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');
}
}
你确实可以使用 timeout 和 switchMap 来链接这两个调用。
return this.apiQueryService.getFirstObj$(name).pipe(
switchMap(firstObj => this.apiQueryService.getSecondObj$(firstObj.link)),
map(secondObj => true),
timeout(5000),
catchError(() => of(false))
);