【发布时间】:2021-09-18 05:05:10
【问题描述】:
在刷新之前我设法获取可观察数据并将其显示在 html 中,但是如果我刷新页面会丢失所有可观察数据,有没有办法保存状态并即使在页面刷新后也能够获取数据。
这是我的共享服务
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { Supplier } from '../components/selectsupplier/selectsupplierObj';
@Injectable({
providedIn: 'root'
})
export class SharedService {
private availablesuppliers = new BehaviorSubject<Supplier[]>(null);
constructor() { }
loadSuppliers(suppliers: Supplier[]){
this.availablesuppliers.next(suppliers);
}
getSuppliers(): Observable<Supplier[]> {
return this.availablesuppliers.asObservable();
}
}
这是我获取数据并显示它的组件
getSupplierID(){
let supplierID = this.route.snapshot.paramMap.get('id');
return (supplierID);
}
ngOnInit() {
// call function on page load
this.report();
this.SupplierID = this.getSupplierID();
// console.log(typeof(this.SupplierID));
// localStorage.setItem('supplierid', this.SupplierID);
this.Auth.authStatus.subscribe(value => this.loggedIn = value);
this.shared.getSuppliers()
.pipe(
map(suppliers =>
// console.log("suppliers", suppliers)
suppliers.filter(supplier => supplier.SupplierID === this.SupplierID),take(1),
)
)
.subscribe(response => {
// console.log("From shared services", response);
// console.log(this.SupplierID);
this.supplier = response;
});
所以在第一次运行时供应商会填充数据,但是当我刷新供应商时返回为空。
更新代码,将数据保存在本地存储中,然后检索显示
ngOnInit() {
// call function on page load
this.report();
this.SupplierID = this.getSupplierID();
// console.log(typeof(this.SupplierID));
// localStorage.setItem('supplierid', this.SupplierID);
this.Auth.authStatus.subscribe(value => this.loggedIn = value);
this.shared.getSuppliers()
.pipe(
map(suppliers =>
// console.log("suppliers", suppliers)
suppliers.filter(supplier => supplier.SupplierID === this.SupplierID),take(1),
)
)
.subscribe(response => {
// console.log("From shared services", response);
// console.log(this.SupplierID);
// this.supplier = response;
localStorage.setItem('supplierObject', JSON.stringify(response));
var retrievedObject = localStorage.getItem('supplierObject');
this.supplier = JSON.parse(retrievedObject);
console.log("Object from localStorage", this.supplier);
});
}
【问题讨论】:
-
By refresh 如果您的意思是页面重新加载,那么是的,浏览器重新加载时数据会丢失,您必须将数据保存在 Web Storage 并在组件加载时检索它,但是注意,如果您使用 localStorage,您还需要手动从存储中删除数据。
-
是的,重新加载时,如果我以正确的方式存储它,请检查最后更新的代码,虽然它在重新加载时不起作用我仍然将地图函数中的(供应商)设为空。
-
shared.getSuppliers()是做什么的?它是一个 API 吗?如果是,那么无论如何调用 API 并获取数据,您都不需要使用存储。
标签: angular observable