gpt4 book ai didi

angular - http-interceptor 等待订阅完成获取数据

转载 作者:行者123 更新时间:2023-12-04 14:40:54 26 4
gpt4 key购买 nike

我有一个 HTTP 拦截器。后端 API 需要自定义 header ,其值在应用初始化和其他操作期间存储在 indexdb 中。因此,我需要获取值并在每个请求中传递它。但到目前为止,未能这样做,因为拦截器不会等待订阅完成执行并发送没有自定义 header 的请求。

intercetpor 确实获得了当前保存的或默认的 header ,但是当请求通过没有 header 时为时已晚。

indexdb.service.ts:

@Injectable()
export class IndexDBService {
/*
Handles configuration of the app:
reading current configuration
saving configuration
*/

private pouch: any;

constructor() {
this.pouch = new PouchDB("config", {
auto_compaction: true
});
}

currentConfig(): Observable<any> {
/*
Return the current configuration saved in the database
*/
let vm = this;
return new Observable(observer => {
vm.pouch.get("info", function(err, doc) {
if (err) {
console.log("config read error ", err);
// create a default one
configOptions={'header1': '1','header2':2}
observer.next(configOptions);
} else {

observer.next(doc);
}
});
});
}
}

拦截器.ts
import { Injectable } from "@angular/core";
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpHeaders
} from "@angular/common/http";
import { Observable } from "rxjs";
import { IndexDBService } from "../services/indexdb.service";

@Injectable()
export class InterceptAPICalls implements HttpInterceptor {
constructor(private indexdbService: IndexDBService) {}

intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {

this.indexdbService.currentConfig().subscribe(configData => {
console.log(configData); // ==> does work great. I am getting data right
req = req.clone({
headers: new HttpHeaders({

"X-Header1": configData["header1"],
"X-Header2": configData["header2"]
})

});
return next.handle(req); // want this one to return always
});
// below is cos the app won't compile and it returns immediately
return next.handle(req);
}
}

最佳答案

拦截函数只需要返回一个可观察的。所以你开始向 currentConfig() 发出请求然后在发出配置时切换到下一个拦截器。

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this.indexdbService
.currentConfig()
.pipe(
first(),
mergeMap(configData => {
req = req.clone({
headers: new HttpHeaders({
'X-Header1': configData['header1'],
'X-Header2': configData['header2']
})
});
return next.handle(req);
})
);
}

关于angular - http-interceptor 等待订阅完成获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56305749/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com