How to pass status from login page to app.componen

2019-08-17 06:09发布

问题:

I want to pass login status from login file to app.component file in ionic where my login file in pages folder.

login.ts

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

as shown in above code i want to pass this status from login file to app.component file

回答1:

Ionic Events will helps you to achieve this. You can publish event in your login.ts with the data and subscribe it to app.component.ts to get data i means whatever your status like this :

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