javascript - วิธีในการยับยั้งคำขอ HTTP บางรายการที่ HTTP Interceptor ใน Angular
ผมมีโค้ด Angular และเรื่องราวเบื้องหลังคือแบบนี้ ผมมีคำสั่ง HTTP 3 ครั้ง และจากคำสั่งหนึ่งผมต้องการ header พิเศษ (X) ซึ่งจำเป็นสำหรับคำสั่ง HTTP อีกสองคำสั่ง แต่ผมไม่สามารถควบคุมการทำงานของคำสั่งเหล่านี้ได้ ดังนั้นเมื่อคำสั่ง HTTP ที่ต้องการ header X ถูกเรียกก่อนคำสั่ง HTTP ที่ให้ header X ผมจะทำอย่างไรเพื่อหยุดคำสั่งนั้นไว้ ให้คำสั่ง HTTP ที่เฉพาะเจาะจงไปและรับ header X และดำเนินคำสั่งที่เหลือต่อด้วยการเพิ่ม header X เข้าไปในคำสั่ง HTTP ที่เหลือ อาจดูเหมือนว่าผมกำลังพยายามสร้างคิวของคำสั่ง HTTP จนกว่าจะได้ header 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 ที่มีการเรียก HTTP ทั้ง 3 ครั้ง
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() ใหม่จากระดับ interceptor
ด้านล่างนี้คือโค้ดของตัวดักจับ
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);
}
ถ้าพวกคุณต้องการคำชี้แจงใด ๆ กรุณาทิ้งข้อความในคอมเมนต์ ถ้าคุณเห็นว่าฉันทำอะไรผิดไปบ้างตรงนี้ กรุณาแชร์ให้ฉันทราบ การปรับปรุงโค้ดใด ๆ ยินดีต้อนรับ
คำตอบ #1
ฉันพบวิธีแก้ปัญหาและมันค่อนข้างดีสำหรับฉันในตอนนี้ ฉันกำลังใช้สตรีมของ SUbject เพื่อเลียนแบบพฤติกรรมของคิวและให้คำขอสะสมจนกว่าฉันจะได้รับข้อมูลจากการเรียก HTTP ที่มี header X ด้านล่างนี้คือโค้ด หวังว่าจะเข้าใจนะ สวัสดี!
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();
};
}
});
