ionic-framework - 使用href并切换回应用程序的离子4丢失会话
问题描述
我构建了一个简单的页面,它呈现了一些项目的列表。这些项目有一个 href 元素可以在浏览器中打开它。问题在于,当用户返回时,所有用于保存局部变量的类都被重新初始化并破坏了应用程序的功能。处理这个问题的正确方法是什么。我想保留数据集。下面是我的列表代码和服务类中的变量
<ion-content>
<div class="full-screen-bg">
<div *ngFor="let alb of core.albums">
<ion-row><ion-col no-padding text-center><a href="{{alb.link}}"><img src="{{alb.image}}"></a></ion-col></ion-row>
<ion-row><ion-col class="sg-title-text">{{alb.name}}</ion-col></ion-row>
</div>
具有变量并被重置的服务类是
@Injectable({
providedIn: 'root'
})
export class CoreService {
loggedIn:boolean
name:string
constructor(public admob: Admob,
public sgSvc:DataServiceService) {
this.loggedIn = false
console.log("album constructor called:::" + this.loggedIn + " name:" + this.name)
}
}
解决方案
简单的方法是通过 StorageService 保存登录用户(用户名、令牌和过期时间),并且对于您的 CoreService 应该尝试从 StorageService 获取并确认它,如果令牌没有或已经超过 exporation time 那么这意味着用户应该登录再次。
export class CoreService {
//...
public isAdmin = false;
private token = false;
public userSubject: Subject<Object> = new Subject<Object>();
//...
constructor(/*...*/) {
this.userSubject.subscribe(user => {
if (user && user['role']) {
if (user['role'] == 'admin') {
this.isAdmin = true;
} else {
this.isAdmin = false;
}
}
});
this.getLocal('user').then(val => {
this.userSubject.next(val);
});
}
//...
}
//And for other component also subscribe same subject like
export class AppComponent /*...*/ {
constructor(coreService: CoreService /*...*/) {
this.coreService.userSubject.subscribe(user => {
// your logic there
});
}
}
推荐阅读
- python - 将 pyautogui 时间设置为秒,即 0.5 秒
- django-models - Django - 更新字段时更新不同表的字段
- r - r中的名称匹配和更正拼写错误
- node.js - 在将 XML 发送到 SOAP API 之前,如何在我的 XML 中放置一些变量?
- google-sheets - 多次向客户展示
- python - 在mpld3中如何使红线可拖动?
- flutter - 颤振:如何在聊天消息的右下角对齐时间
- react-admin - React admin导入按钮referenceManyField?
- python - 使用 Seaborn `displot`(不是 `distplot`)在同一图表上绘制多个直方图
- r - 从命令行渲染 R markdown。Bash 脚本中的错误 - 没有这样的文件或目录