【发布时间】:2019-07-10 02:24:54
【问题描述】:
我有一个 Angular 代码,背后的故事是这样的。我有 3 个 HTTP 调用,从一个调用中我需要一个特殊的标头 (X),这是其他两个 HTTP 调用所需的,我无法控制这些调用的执行。因此,当需要 X 标头的 HTTP 调用在给我 X 标头的 HTTP 调用之前进行时,我如何才能推迟调用并让特定的 HTTP 调用继续获取 X 标头并继续其余的调用附加到其余 HTTP 调用的 X 标头?看起来我正在尝试创建一个 HTTP 调用队列,直到我得到 X 标头并再次继续其余的调用。一些帮助将不胜感激。代码如下。
模板:
<button class="btn btn-primary" (click)="do()"> Do </button>
App.ts 文件
export class AppComponent {
constructor(private dataService: DataService) {}
public do(): void {
this.dataService.first().subscribe();
this.dataService.second().subscribe((res) => {
this.dataService.third().subscribe();
});
}
}
data-service.ts 有 3 个 HTTP 调用
const httpOptions1 = {
headers: new HttpHeaders({ 'A': 'A' })
};
const httpOptions2 = {
headers: new HttpHeaders({ 'X': 'X' })
};
const httpOptions3 = {
headers: new HttpHeaders({ 'B': 'B' })
};
@Injectable()
export class DataService {
private apiUrl = 'https://jsonplaceholder.typicode.com/posts';
constructor(private http: HttpClient) {}
public first(): Observable<any> {
console.log('Call One')
return this.http.get(`${this.apiUrl}`, httpOptions1);
}
public second(): Observable<any> {
console.log('Call Two')
return this.http.get(`${this.apiUrl}`, httpOptions2);
}
public third(): Observable<any> {
console.log('Call Three')
return this.http.get(`${this.apiUrl}`, httpOptions3);
}
}
这是第二个调用,它有我的 X 标头,从拦截器我想做的是,当 first() 调用关闭时,我想保持它添加并让 second() 调用去获取X 标头,然后从拦截器级别重新运行first() 调用。
下面是拦截器的代码
private pocessed: boolean = false;
private queue: any[] = [];
constructor() {}
public intercept(req: HttpRequest<any>, delegate: HttpHandler): Observable<any> {
/**
* Filter a certain http call with a certain X http header where this call provides a new header
* to be appended to all other http calls
*/
if (req.headers.has('X')) {
return delegate.handle(req).do((event) => {
if (event.type === HttpEventType.Response) {
// new header data acquired; hence the boolean turned to true
this.pocessed = true;
}
});
} else if (this.pocessed) {
/**
* if new header data acquired, append the new header to the rest of the calls
*/
if (this.queue.length > 0) {
// append header data to previous http calls
this.queue.forEach(element => {
let request = new HttpRequest(element.req['method'], element.req['url'], element.req['body'], {
headers: element.req['headers'],
reportProgress: true,
params: element.req['params'],
responseType: element.req['responseType'],
withCredentials: element.req['withCredentials']
});
// this.fakeIntercept(request, element.next);
});
}
// if new header data acquired, append the header to the rest of the calls
req = req.clone({ setHeaders: { 'X': 'X' } });
return delegate.handle(req).do((event) => console.log(event));
} else {
/**
* these http calls need X header but the call to get the X header hasnt gone yet
* therefor storing these calls in a queue to be used later when the header arrives
*/
this.queue.push({req: req, next: delegate});
return Observable.empty<any>();
}
}
fakeIntercept(req: HttpRequest<any>, delegate: HttpHandler): Observable<any> {
req = req.clone({ setHeaders: { 'X': 'X' } });
return delegate.handle(req);
}
如果你们需要任何澄清,请在 cmets 中联系我。如果您发现我在这里做错了什么,请与我分享。欢迎对代码进行任何改进。
【问题讨论】:
-
调用第一个...获取标题并执行其他调用,为什么要保持调用。
-
@mahi 我无法控制通话的进行方式。它们是动态弹出的,除了将它们置于提示中之外,我无法控制它们
-
对于第一次调用,您将获得包含其他两个调用使用的一些标头对象的响应 json。我说的对吗
-
@mahi 它并不总是第一个电话。这就是为什么我需要推迟其他电话。这里我只是模仿了 app.component.ts 中的实际行为
标签: javascript angular typescript http angular-http-interceptors