我有一个Angular代码,后面的故事就是这样。我有3个HTTP调用,而从一个调用中,我需要另外两个HTTP调用所需的特殊标头(X),但我无法控制这些调用的执行。因此,当需要X标头的HTTP调用出现在给我X标头的HTTP调用之前时,我该如何推迟该调用并放开特定的HTTP调用并获取X标头,并继续使用X标头附加到其余的HTTP调用中?似乎我正在尝试创建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标头的调用,我想从Interceptor中进行的操作是,当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);
}
如果你们需要任何澄清,请在评论中打我。如果您发现我在这里做错了什么,请与我分享。欢迎对代码进行任何改进。
答案 0 :(得分:0)
我找到了一个解决方案,它对我的atm很好。我正在使用SUbject流来模仿Queue的行为,并让请求堆积起来,直到从X标头http调用获取数据为止。下面是代码。希望有道理。干杯!
public intercept(req: HttpRequest<any>, delegate: HttpHandler): Observable<any> {
return Observable.create(observer => {
if (req.headers.has('X') && this.headerAcquired == false) {
this.headerAcquired = true;
const subscription = delegate.handle(req).subscribe(event => {
if (event instanceof HttpResponse) {
this.pocessed = true;
this.requestSetter({key: this.pocessed});
this.removeRequest(req);
observer.next(event);
}
},
err => {
this.removeRequest(req);
observer.error(err);
},
() => {
this.removeRequest(req);
observer.complete();
});
// remove request from queue when cancelled
return () => {
this.removeRequest(req);
subscription.unsubscribe();
};
} else {
this.requests.push(req);
this.requestGetter().subscribe(res => {
const i = this.requests.indexOf(req);
if (i >= 0) {
this.subjectInit = true;
this.requests.splice(i, 1);
req = req.clone({ setHeaders: { 'X': 'X' } });
const subscription = delegate.handle(req).subscribe(event => {
if (event instanceof HttpResponse) {
this.pocessed = true;
this.request.next(true);
this.removeRequest(req);
observer.next(event);
}
},
err => {
this.removeRequest(req);
observer.error(err);
},
() => {
this.subjectInit = false;
this.removeRequest(req);
observer.complete();
});
// remove request from queue when cancelled
return () => {
this.removeRequest(req);
subscription.unsubscribe();
this.request.unsubscribe();
};
}
});