我有一个data.service.ts
文件,用于存储在我的 Angular 项目中的许多组件之间共享的变量。
import { Injectable } from '@angular/core';
@Injectable()
export class myService {
public sharedData:string;
constructor(){
this.sharedData = "String from myService";
}
setData (data) {
this.sharedData = data;
}
getData () {
return this.sharedData;
}
}
Run Code Online (Sandbox Code Playgroud)
myService
并且仅在文件上的“providers”中创建了一次类( )app.module.ts
并导入了可注入文件:data.service.ts
我在组件中使用 get 和 set 方法,这工作得很好。但是当我重新加载或刷新页面时,该值就消失了。我已经看到建议使用的解决方案localStorage
,但是是否有另一种方法可以在刷新后保持值的持久性。