如何解决Angular UniversalSSR无法识别带有自定义httprxjs ajax,axios的请求
我在使用自定义库的角度应用程序中工作,该自定义库向服务器发出请求并获取数据。该库使用rxjs ajax方法进行调用,并且被其他非角度应用程序使用,这就是为什么不使用角度httpClient将其作为角度库创建的原因。
虽然库在浏览器上运行并且所有请求都正确返回了数据,但是当我尝试使其与角度通用一起工作时会出现问题,因为没有在服务器端检索数据,或者至少角度不知道其中。该应用程序呈现后,浏览器又重新控制了请求,请求再次开始工作。
这是我如何在库中进行请求的摘录
export class RestMethods {
constructor(
private createXHR?: () => XMLHttpRequest
) {}
private restRequest(options: RestRequestOptions): Observable<any> {
let requestOptions: AjaxRequest = {
method: options.method,url: options.url,body: options.body,headers: { ...options.headers },};
if (this.createXHR || options.createXHR) {
requestOptions.createXHR = options.createXHR || this.createXHR;
}
if (options.withCredentials !== null && typeof options.withCredentials !== 'undefined') {
requestOptions.withCredentials = options.withCredentials;
}
return ajax(requestOptions).pipe(
tap((res) => console.log('res',res)),map((res) => {
let response = res.response;
return response;
}),catchError((error) => {
let errorData: RestRequestError = errorFormatter(error);
return throwError(errorData);
})
);
}
getRequest(url: string,reqHeaders?: any,options?: MethodsOptions): Observable<any> {
const { headers,...reqOpts } = options || {};
return this.restRequest({ method: 'GET',url: url,headers: reqHeaders,...reqOpts });
}
postRequest(url: string,body?: any,reqHeaders?: object,...reqOpts } = options || {};
return this.restRequest({
method: 'POST',body: body,headers: {'Content-Type': 'application/json',...reqHeaders},...reqOpts,});
}
}
和方法示例:
getStores(options?: MethodsOptions): Observable<Store[]> {
return this.xrest
.getRequest(
`${this.mainUrl}/stores?language=${this.languageId}`,{ ...this.headers,...options?.headers },{ ...options }
)
.pipe(map((data: any) => data)));
}
我还尝试过使用axios,以检查rxjs ajax方法是否存在问题并将ssr包装到可观察对象中。
private request(options) {
console.log('axios request');
let requestOptions: AxiosRequestConfig = {
method: options.method,data: options.body,};
if (options.withCredentials !== null && typeof options.withCredentials !== 'undefined') {
requestOptions.withCredentials = options.withCredentials;
}
return from(
axios(requestOptions)
.then((res) => {
console.log('axios promise resolved',res)
return res;
})
.catch((e) => {
console.log('error');
return e;
})
).pipe(
map((res) => {
let response = res;
console.log('axios observable',response);
return response;
}),catchError((error) => {
let errorData: RestRequestError = errorFormatter(error);
console.error(errorLog);
return throwError(errorData);
})
);
}
切换到axios之后,我可以发现请求实际上是发出的,因为打印了then块内的console.log,但从未到达rxjs管道内的其他对象。因此,我可以猜到问题是,角度ssr并不知道此请求完成。
有什么办法可以做到这一点?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。