Вам необходимо поделиться некоторой информацией между двумя вашими компонентами, т. Е. Когда выполняется запрос на опрос, а когда нет.Вы должны использовать Сервис для этого.Также всегда полезно перенести логику http-запроса в службу вместо использования HttpClient непосредственно в компоненте.Это позволяет вам выполнять общую обработку ошибок в одном месте.Давайте назовем этот сервис ApiService.
ApiService
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, BehaviorSubject, interval } from 'rxjs';
import { switchMap, tap } from 'rxjs/operators';
@Injectable({ providedIn: 'root' })
export class ApiService {
// Use a BehaviorSubject to notify listeners about ongoing polling requests.
// A BahaviorSubject always has a current value that late subscribers will
// receive immediately upon subscribing
private pollRequestInProgress = new BehaviorSubject<boolean>(false);
// Share this BehaviorSubject as an Observable
public pollRequestInProgress$ = pollRequestInProgress.asObservable();
constructor(private http: HttpClient)
doPoll(url: string): Observable<any> {
return interval(3000).pipe( // interval(3000) is equivalent to timer(3000, 3000)
tap(_ => pollRequestInProgress.next(true)), // notify that a poll request is about to happen
switchMap(_ => this.http.get(url)), // do your poll request
tap(_ => pollRequestInProgress.next(false)) // notify that your poll request ended
);
}
}
MainComponent
Это компонент, с которого вы хотите начать опрос.
private destroy$: Subject<void> = new Subject<void>();
constructor(private apiService: ApiService) {}
// move logic to ngOnInit instead of constructor
ngOnInit() {
// subscribe and thereby start the polling
this.apiService.doPoll(URL).pipe(takeUntil(this.destroy$))
.subscribe(pollResponse => {
//DO SOMETHING
});
}
ngOnDestroy() {
// unsubscribe when the Component gets destroyed.
this.destroy$.next();
this.destroy$.complete();
}
FeatureComponent
Это компонент, в котором вы хотите выполнить http-запрос при нажатии кнопки.
constructor(private http: HttpClient, private apiService: apiService) {}
submit() {
// Listen to whether a polling request is currently in progress.
// We will immediately receive a value upon subscribing here, because we used
// a BehaviorSubject as the underlying source.
this.apiService.pollRequestInProgress$.pipe(
// Emit the first item that tells you that no polling request is in progress.
// i.e. let the first 'requestInProgress === false' through but not any
// other items before or after.
first(requestInProgress => !requestInProgress),
// If no polling request is in progress, switch to the http request you want
// to perform
switchMap(this.http.get("/sumbitForm")) // <-- consider moving this http.get to your ApiService aswell
).subscribe(httpResponse => {
// you've got your http response here
});
// you don't have to unsubscribe here as first and http.get both complete
// and thus unsubscribe automatically
}
Посмотрите простой пример приведенной выше логики кода: https://stackblitz.com/edit/rxjs-t4hjcr