ionic 4使用href丢失会话并切换回应用

时间:2019-02-01 02:41:49

标签: ionic-framework ionic4

我建立了一个简单的页面,它呈现了一些项目的列表。这些项目具有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)
  }
}

1 个答案:

答案 0 :(得分:1)

最简单的方法是通过StorageService保存登录用户(用户名,令牌和到期时间),对于您的CoreService,应尝试从StorageService获取它并进行确认,如果令牌不是令牌或令牌已过期,则表示用户是普通用户应该再次登录。

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
    });
  }
}