我已经用Angular Universal设置了Angular 8项目。为了防止重复的HTTP调用,Angular提供了 TransferHttpCacheModule 。
我遵循官方文档将 TransferHttpCacheModule 添加到Angular(https://github.com/angular/universal/blob/master/docs/transfer-http.md)
我还尝试添加 BrowserTransferStateModule (https://www.twilio.com/blog/faster-javascript-web-apps-angular-universal-transferstate-api-watchdog),但这也不起作用。
app.module.ts
import {BrowserModule} from '@angular/platform-browser';
import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {TransferHttpCacheModule} from "@nguniversal/common";
@NgModule({
declarations: [
AppComponent,
...
],
imports: [
BrowserModule.withServerTransition({appId: 'serverApp'}),
TransferHttpCacheModule, // <-
...
HttpClientModule
]
bootstrap: [AppComponent]
})
export class AppModule {
}
app.server.module.ts
import {NgModule} from '@angular/core';
import {ServerModule, ServerTransferStateModule} from '@angular/platform-server';
import {AppModule} from './app.module';
import {AppComponent} from './app.component';
import {ModuleMapLoaderModule} from '@nguniversal/module-map-ngfactory-loader';
@NgModule({
imports: [
AppModule,
ServerModule,
ModuleMapLoaderModule,
ServerTransferStateModule // <-
],
bootstrap: [AppComponent],
})
export class AppServerModule {
}
main.ts
document.addEventListener('DOMContentLoaded', () => {
platformBrowserDynamic()
.bootstrapModule(AppModule)
.catch(err => console.error(err));
});
我的Api服务 api.service.ts
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from "rxjs";
@Injectable({
providedIn: 'root'
})
export class ApiService {
private API_URL = '/api/';
constructor(private http: HttpClient) {
}
public get<T>(url: string): Observable<T> {
return this.http.get<T>(this.API_URL + url);
}
public post<T>(url: string, payload: T): Observable<T> {
return this.http.post<T>(this.API_URL + url, payload);
}
...
}
HTTP调用 home.component.ts
import {Component, OnInit} from '@angular/core';
import {ApiService} from "../../api.service";
import {Offer} from "../../offer-preview/offer.model";
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.sass']
})
export class HomeOffersComponent implements OnInit {
latestOffers: Offer[];
constructor(private apiService: ApiService) {
}
ngOnInit() {
this.apiService.get<Offer[]>("offer")
.subscribe(data => this.latestOffers = data);
}
}
根据正式的TransferHttpCacheModule文档,浏览器不应将XHR制作为 / api / offer ,但我会在开发人员网络工具中看到XHR调用。
我在做什么错?我有想念吗?