首页 > 解决方案 > 使用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)
  }
}

标签: ionic-frameworkionic4

解决方案


简单的方法是通过 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
    });
  }
}

推荐阅读