使用这几个模块,可以解决 http请求在服务端和客户端分别请求一次 的问题。
比如在 home.component.ts 中有如下代码:
import { Component, OnDestroy, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit, OnDestroy {
constructor(public http: HttpClient) {
}
ngOnInit() {
this.poiSearch(this.keyword, '北京市').subscribe((data: any) => {
console.log(data);
});
}
ngOnDestroy() {
}
poiSearch(text: string, city?: string): Observable<any> {
return this.http.get(encodeURI(`http://restapi.amap.com/v3/place/text?keywords=${text}&city=${city}&offset=20&key=55f909211b9950837fba2c71d0488db9&extensions=all`));
}
}
代码运行之后,
服务端请求并打印:

客户端再一次请求并打印:

方法1:使用 TransferHttpCacheModule
使用 TransferHttpCacheModule 很简单,代码不需要改动。在 app.module.ts 中导入之后,Angular自动会将服务端请求缓存到客户端,换句话说就是服务端请求到数据会自动传输到客户端,客户端接收到数据之后就不会再发送请求了。
方法2:使用 BrowserTransferStateModule
该方法稍微复杂一些,需要改动一些代码。
调整 home.component.ts 代码如下:
import { Component, OnDestroy, OnInit } from '@angular/core';
import { makeStateKey, TransferState } from '@angular/platform-browser';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
const KFCLIST_KEY = makeStateKey('kfcList');
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit, OnDestroy {
constructor(public http: HttpClient,
private state: TransferState) {
}
ngOnInit() {
// 采用一个标记来区分服务端是否已经拿到了数据,如果没拿到数据就在客户端请求,如果已经拿到数据就不发请求
const kfcList:any[] = this.state.get(KFCLIST_KEY, null as any);
if (!this.kfcList) {
this.poiSearch(this.keyword, '北京市').subscribe((data: any) => {
console.log(data);
this.state.set(KFCLIST_KEY, data as any); // 存储数据
});
}
}
ngOnDestroy() {
if (typeof window === 'object') {
this.state.set(KFCLIST_KEY, null as any); // 删除数据
}
}
poiSearch(text: string, city?: string): Observable<any> {
return this.http.get(encodeURI(`http://restapi.amap.com/v3/place/text?keywords=${text}&city=${city}&offset=20&key=55f909211b9950837fba2c71d0488db9&extensions=all`));
}
}
内容版权声明:除非注明,否则皆为本站原创文章。
