在Angular 6应用中多次发送了Http请求

时间:2018-11-01 14:44:39

标签: angular httprequest rxjs6 angular-http-interceptors

在我们的angular 6应用程序中,我注意到一些Http GET调用至少执行了两次。有时,OPTIONS和/或第一个GET被取消,只有第二个调用成功。在其他情况下,相同的GET调用将执行两次或更多次。

enter image description here

页脚组件调用服务以获取当前应用程序版本并显示其模板。一个简单的带订阅的Observable,无需任何特殊运算符。

更新
经过进一步调查,问题似乎出在HttpInterceptor中的combineLatest上。由于这两个可观察对象是由一个BehaviourSubject(每个)作为可观察对象发出的,所以我猜想这些Subject发出时的速度/时间是不同的,因此,使CombineLates触发两次或更多次。

模仿者服务(从行为主题中观察到)

export class ImpersonatorService {
public get changeHandler(): Observable<string> {
    return this.changeHandlerInternal.asObservable();
}

private changeHandlerInternal = new BehaviorSubject<string>(this.get());
private key = "impersonate";
constructor(private cookieService: CookieService) {}

public set(impersonate: string) {
    this.cookieService.put(this.key, impersonate);
    this.changeHandlerInternal.next(impersonate);
}

private get(): string {
    let impersonate = this.cookieService.get(this.key);
    if (impersonate === undefined || impersonate === null || impersonate === "") {
        impersonate = "";
    }

    return impersonate;
}
}

脚组件

export class FooterComponent implements OnInit {
public applicationInfo: Observable<ApplicationInfo>;

constructor(private applicationService: ApplicationInfoService) {}

ngOnInit() {
    this.applicationInfo = applicationService.getApplicationInfo();
  }
}

页脚模板

<div>
    {{ (applicationInfo | async)?.version }}
</div>

应用服务

export class ApplicationInfoService {
constructor(private http: HttpClient, @Inject(APP_CONFIG) private config: IAppConfig) {}

public getApplicationInfo(): Observable<ApplicationInfo> {
    return this.http.get<ApplicationInfo>(this.config.apiEndpoint + "/api/applicationinfo");
   }
}

仅从页脚组件调用应用程序服务。

我们还使用HttpInterceptor注入标头:

export class HttpInterceptor implements HttpInterceptor {
constructor(private impersonator: ImpersonatorService, private profileService: ProfileService, private languageService: TranslateService) {}

public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return this.impersonator.changeHandler
        .combineLatest(this.profileService.changeHandler, (user, profile) => {
            let customHeaders = req.headers.set("X-Impersonate", user).set("X-Profile", profile);

            if (customHeaders.has("Content-Type")) {
                if (customHeaders.get("Content-Type") === "multipart/form-data") {
                    customHeaders = customHeaders.delete("Content-Type");
                }
            } else {
                customHeaders = customHeaders.set("Content-Type", "application/json");
            }

            const clonedReq = req.clone({ headers: customHeaders, withCredentials: true });
            return next.handle(clonedReq);
        })
        .switch();
    }
}

从其他SO响应中读取,似乎与种族问题有关。但是,发现的其他情况是使用switchMap或其他运算符导致这些情况下的问题。

通过调试,我可以看到在HttpInterceptor内部有两个对ApplicationInfo端点的请求。但是如何确保没有重复的请求发送?

0 个答案:

没有答案