我创建了一个登录页面,成功登录,并获取了一个授权密钥,然后将其存储到本地存储中。现在,我想将URL中而不是标头中的授权密钥传递给登录后发出的所有请求。我该怎么办?
答案 0 :(得分:1)
我创建了一个堆栈闪电作为示例,使用拦截器添加一些参数
请参见https://stackblitz.com/edit/angular-jqs7wu
修改:添加了相关代码
这只是一个带有1个查询参数(QuestionService)的基本http请求
fetchQuestions(topic: string): Observable<any[]> {
const params = new HttpParams().append('intitle', topic);
return this.http.get<any[]>("https://api.stackexchange.com/2.2/search", { params });
}
拦截器(QuestionInterceptor)在将请求提交到网络之前向请求添加了其他一些参数
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const params = req.params
.append('pagesize', String(pagesize))
.append('site', site)
.append('order', order)
.append('sort', sort); // append your auth key here instead of those params
const cloneReq = req.clone({ params });
return next.handle(cloneReq);
}