怎么做“ ngIf localstorage”数据绑定

时间:2018-07-22 12:07:04

标签: angular ionic-framework ionic3

我有一个ionic 3应用程序,它有一个侧面菜单,位于app.html中。

如果用户未登录,则应该在菜单中看到登录名ion-button。如果用户已登录,则登录按钮应该消失,而应该看到注销按钮和受保护的example页面。

login.ts

     onLogin() {
    console.log(this.username, this.password);
    this.authProvider.postLogin(this.username, this.password).subscribe(data => {
      console.log(data);
      localStorage.setItem('wpIonicToken', JSON.stringify(data));
      if (localStorage.getItem('wpIonicToken')) {
        this.navCtrl.push(HomePage);
      }
    });
  }
 }

app.htm

<div *ngIf="token==true">
      <ion-buttons class="log-out" end>
        <button ion-button text-lowercase icon-right clear menuClose (click)="logout()">
          Logout
          <ion-icon color="grayColor" name="ios-log-out" large></ion-icon>
        </button>
      </ion-buttons>
    </div>
    <div *ngIf="token==false">
      <ion-buttons class="log-out" end>
        <button ion-button text-lowercase icon-right clear menuClose (click)="goTo('LoginPage')">
          Login
          <ion-icon color="grayColor" name="ios-log-in" large></ion-icon>
        </button>
      </ion-buttons>
    </div>

app.component.ts

token: boolean = false;
if (localStorage.getItem('wpIonicToken')) {
  this.token = true;
}
else {
  this.token = false;
}
  logout() {
  localStorage.clear();
  this.navCtrl.push('HomePage');
  }

问题在于,当用户登录或注销时,除非我刷新浏览器,否则token不会更新,因此项目保留在菜单中,当刷新浏览器时,菜单也会更新。

>

2 个答案:

答案 0 :(得分:1)

尝试类似这样的方法。

login.ts

onLogin() {
console.log(this.username, this.password);
this.authProvider.postLogin(this.username, this.password).subscribe(data => {
  console.log(data);
  localStorage.setItem('wpIonicToken', JSON.stringify(data));
  if (localStorage.getItem('wpIonicToken')) {
    this.navCtrl.push(HomePage);

  }

   this.messageService.broadcast('tokenChanged', {data: data}); //<== add this
});
  }
 }

app.ts

token: boolean = false;

constructor(private messageService: MessageService){
this.messageService.myAppEvent$.subscribe(ev => {
  if (ev.type == 'tokenChanged')
  {
    this.token = ev.data;
  }
});
}
//...

  logout() {
   this.messageService.broadcast('tokenChanged', {data: null});
  this.navCtrl.push('HomePage');
  }  

这样定义消息传递服务

export class MyAppEvent
{
  type: string;
  data: any;
}


@Injectable()
export class MessageService
{
  private myAppEventSubject: Subject<MyAppEvent> = new Subject<MyAppEvent>();
  public readonly myAppEvent$: Observable<MyAppEvent> = this.myAppEventSubject.asObservable();

  broadcast(name: string, data)
  {
    this.myAppEventSubject.next( {type: name,   data: data });
  }
}     

答案 1 :(得分:0)

此处 this.nav? 是什么意思。您可以直接使用 router.navigate

constructor(private router: Router) {}

  logout() {
     this.navCtrl.push('HomePage');
     localStorage.clear();
  }