如何将状态从登录页面传递到ionic中的app.component

时间:2019-06-13 15:29:43

标签: ionic-framework

我想将登录状态从登录文件传递给ionic中的app.component文件,其中我的登录文件位于pages文件夹中。

login.ts

this.http.post('http://localhost:80',{
      "username": email,
      "password": password
      }).subscribe((data: any) => {
    if(data.status === 'success'){
      this.navCtrl.navigateRoot('/home');
}

如上面的代码所示,我想将此状态从登录文件传递到app.component文件

1 个答案:

答案 0 :(得分:0)

Ionic Events将帮助您实现这一目标。您可以使用数据在login.ts中发布事件,并将其订阅到app.component.ts以获取数据,我的意思是您的状态如何:

login.ts

import { Events } from 'ionic-angular';
...
...
constructor(public events: Events) {}

yourMethod() {
    this.http.post('http://localhost:80',{
        "username": email,
        "password": password
    }).subscribe((data: any) => {
        if(data.status === 'success'){
            this.navCtrl.navigateRoot('/home');
            this.events.publish('eventName', data);
        }
    }
}

app.component.ts

import { Events } from 'ionic-angular';
...
...
constructor(public events: Events) {
    events.subscribe('eventName', (data) => {
        // data is the same that your have passed when you published the event
        console.log('data', JSON.stringify(data));
    });
}