使用Rxjs Observer / Observable +缓存+订阅的可缓存HTTP响应数据
请参阅下面的代码
*免责声明:我是rxjs的新手,所以请记住,我可能会滥用可观察/观察者方法。我的解决方案纯粹是我找到的其他解决方案的综合,并且是未能找到简单的有据可查的解决方案的结果。因此,我提供了完整的代码解决方案(正如我希望发现的那样),希望对其他人有所帮助。
*请注意,这种方法大致基于GoogleFirebaseObservables。不幸的是,我缺乏适当的经验/时间来复制他们在幕后所做的事情。但是以下是提供对某些可缓存数据的异步访问的简单方法。
情况:“产品列表”组件的任务是显示产品列表。该站点是一个单页Web应用程序,带有一些菜单按钮,这些按钮将“过滤”页面上显示的产品。
解决方案:组件“订阅”服务方法。service方法返回一个产品对象数组,组件可通过订阅回调访问该对象。service方法将其活动包装在新创建的Observer中,并返回观察者。在此观察器内部,它搜索高速缓存的数据,并将其传递回订阅者(组件)并返回。否则,它将发出http调用以检索数据,订阅响应,在此您可以处理该数据(例如,将数据映射到您自己的模型),然后将数据传递回订阅者。
编码
产品列表.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { ProductService } from '../../../services/product.service';
import { Product, ProductResponse } from '../../../models/Product';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.scss']
})
export class ProductListComponent implements OnInit {
products: Product[];
constructor(
private productService: ProductService
) { }
ngOnInit() {
console.log('product-list init...');
this.productService.getProducts().subscribe(products => {
console.log('product-list received updated products');
this.products = products;
});
}
}
产品服务
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Observable, Observer } from 'rxjs';
import 'rxjs/add/operator/map';
import { Product, ProductResponse } from '../models/Product';
@Injectable()
export class ProductService {
products: Product[];
constructor(
private http:Http
) {
console.log('product service init. calling http to get products...');
}
getProducts():Observable<Product[]>{
//wrap getProducts around an Observable to make it async.
let productsObservable$ = Observable.create((observer: Observer<Product[]>) => {
//return products if it was previously fetched
if(this.products){
console.log('## returning existing products');
observer.next(this.products);
return observer.complete();
}
//Fetch products from REST API
console.log('** products do not yet exist; fetching from rest api...');
let headers = new Headers();
this.http.get('http://localhost:3000/products/', {headers: headers})
.map(res => res.json()).subscribe((response:ProductResponse) => {
console.log('productResponse: ', response);
let productlist = Product.fromJsonList(response.products); //convert service observable to product[]
this.products = productlist;
observer.next(productlist);
});
});
return productsObservable$;
}
}
product.ts(模型)
export interface ProductResponse {
success: boolean;
msg: string;
products: Product[];
}
export class Product {
product_id: number;
sku: string;
product_title: string;
..etc...
constructor(product_id: number,
sku: string,
product_title: string,
...etc...
){
//typescript will not autoassign the formal parameters to related properties for exported classes.
this.product_id = product_id;
this.sku = sku;
this.product_title = product_title;
...etc...
}
//Class method to convert products within http response to pure array of Product objects.
//Caller: product.service:getProducts()
static fromJsonList(products:any): Product[] {
let mappedArray = products.map(Product.fromJson);
return mappedArray;
}
//add more parameters depending on your database entries and constructor
static fromJson({
product_id,
sku,
product_title,
...etc...
}): Product {
return new Product(
product_id,
sku,
product_title,
...etc...
);
}
}
这是我在Chrome中加载页面时看到的输出示例。请注意,在初始加载时,会从http(调用我的节点休息服务,该服务在端口3000上本地运行)中获取产品。然后,当我单击导航到产品的“过滤”视图时,将在缓存中找到产品。
我的Chrome日志(控制台):
core.es5.js:2925 Angular is running in the development mode. Call enableProdMode() to enable the production mode.
app.component.ts:19 app.component url: /products
product.service.ts:15 product service init. calling http to get products...
product-list.component.ts:18 product-list init...
product.service.ts:29 ** products do not yet exist; fetching from rest api...
product.service.ts:33 productResponse: {success: true, msg: "Products found", products: Array(23)}
product-list.component.ts:20 product-list received updated products
... [单击菜单按钮以过滤产品] ...
app.component.ts:19 app.component url: /products/chocolatechip
product-list.component.ts:18 product-list init...
product.service.ts:24 ## returning existing products
product-list.component.ts:20 product-list received updated products
结论:这是到目前为止(到目前为止)实现可缓存的HTTP响应数据的最简单方法。在我的角度应用程序中,每次导航到产品的不同视图时,都会重新加载产品列表组件。ProductService似乎是一个共享实例,因此在导航期间会保留ProductService中'products:Product []'的本地缓存,并且随后对“ GetProducts()”的调用将返回缓存的值。最后一点,我已经读过有关在完成防止“内存泄漏”后需要关闭可观察对象/订阅的评论。我没有在此包括它,但要记住这一点。