Loading data from provider on View opening

Hi everyone,

I have a main page in which i want to load data from a provider. This provider is fetching the data from a Firebase db. My problem is that i can not fetching my data during the page opening.

I tried to call fetching data function in ionViewLoaded, ionViewWillEnter, ionViewDidEnter and in the constructor but my data does not load in the view. The only thing that works is to create a button and call my function on it…

Do you have an idea ?

Thanks

It would certainly help us help you if you could provide some code.

1 Like

Asynchronous reactive programming is a completely different world from the imperative thought style that you are probably accustomed to. In a reactive world, when you request something (such as “call fetching data function”) does not determine when you receive it.

Yes i know, i don’t have the good reflex yet :confused:

Here is my sample code :

In my provider i have the following function which retrieve data from my firebase database :

@Injectable()
export class Dbservice {
    private users: User[] = [];    
    //...

    fetchData(token: string, listType: string){

    const userId = this.authService.getActiveUser().uid;
        return this.http.get('https://mydb-9954c.firebaseio.com/' + userId + '/'+listType+'.json?auth=' + token)
        .map((response: Response) => {
            return response.json();
        })
        .do((users: User[]) => {
             if (users) {
                 this.users = users
             } else {
                 this.users = [];
             }
     });
}

And in my main page

export class myMainPage implements OnInit{
//...
    users: User[] = [];

    constructor(public navCtrl: NavController, 
          public navParams: NavParams, 
          private dbService: Dbservice,
          private alertCtrl: AlertController,
          private authService: AuthService,
          private loadingCtrl: LoadingController){ }

    ngOnInit() {
        this.onFetchData(); // Here is my trouble
    }

    onFetchData(){
      
        const loading = this.loadingCtrl.create({content: 'loading...'});
        loading.present();

     this.authService.getActiveUser().getToken()
        .then(
            (token: string) => {
            this.dbService.fetchData(token,Config.LIST_TYPE[0])
                .subscribe(
                (userList: User[]) => {
                    loading.dismiss();
                    if(userList){
                        this.users = userList;
                    } else {
                        this.users = [];
                    }
                },
                error => {
                    loading.dismiss();
                    alert(error.json().error);
                });
            }
        );
    
     }
}

The error is that my firebase does not seems completely initialized when i call my onFetchData function in ngOnInit, but i do not understand why it works if i call it on a button click event…