我制作了一个站点,该站点也可以与Angular 8一起用作PWA。我也将Angular Universal用于SSR。它可以离线运行。问题在于仅缓存站点,而服务器不缓存。我将dataGroups
添加到了ngsw设置中。
这些是我的 ngsw-config.json
{
"$schema": "./node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"dataGroups": [
{
"name": "exercises-requests",
"urls": [
"/api/provide-exercise"
],
"cacheConfig": {
"strategy": "performance",
"maxSize": 100,
"maxAge": "3d"
}
}
],
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/*.css",
"/*.js"
]
}
},
{
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**",
"/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
]
}
}
]
}
这是我的 http服务:
import { Injectable, isDevMode } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { throwError, Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Input } from '../exercise/exercise.service';
export interface UserInfo {
// ...
}
export interface ProvideExerciseBody {
// ...
}
export interface ProvideExerciseResponse {
// ...
}
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
@Injectable({
providedIn: 'root',
})
export class HttpService {
get
serverDomain(): string {
return isDevMode() ? 'https://unitn-statistica.herokuapp.com' : '';
}
constructor(private http: HttpClient) { }
provideExercise(body: ProvideExerciseBody): Observable<ProvideExerciseResponse> {
return this.http.post<ProvideExerciseResponse>(this.serverDomain + '/api/provide-exercise', body, httpOptions)
.pipe(
catchError(this.handleError)
);
}
private handleError(err: HttpErrorResponse) {
const error = err.error;
if (error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.message);
console.error(error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${err.status}, ` +
`body was: ${error}`);
console.log(error);
}
// return an observable with a user-facing error message
return throwError(error.message);
}
}
我确定服务器调用正确
app.post('/api/provide-exercise', (req, res) => { ... }
我不明白为什么我对服务器的发帖请求没有被缓存。
答案 0 :(得分:3)
我认为您面临的问题是Angular的Service Worker不会缓存POST请求,无论其配置如何。原因是POST请求通常是为了突变服务器上的资源。因此,缓存此请求并不是真正有用。
这是代码的相关部分,其中不包括任何变异请求:https://github.com/angular/angular/blob/master/packages/service-worker/worker/src/data.ts#L283
也许您可以控制服务器,并且发出的请求没有任何变化。那么使用GET请求可能是一个很好的解决方案。
但是,如果请求确实在改变某些东西,但您仍然希望缓存响应,那么使用另一种缓存策略(例如localStorage
或IndexedDB
)可能是一种解决方案。