How to ensure meteor local collection is ready before routing

159 views Asked by At

I am using Meteor + AngularJS framework.

I want to control routing according to what data stored in an offline collection(using ground:db), but the offline data is not guaranteed to be ready before routing.

If the collection is not offline, there seemed to be some ways like "waitOn" or "subscriptionReady" worth researching, but offline collections need no subscriptions or publications, how can I ensure them to be ready, before routing or before the app is bootstrapped?

Key source fragments:

1.route.js

import { LastLogin } from '../lib/collections';

angular.module('app')
    .config(function ($stateProvider, $urlRouterProvider) {
            console.log(LastLogin.find().count());
            if(LastLogin.find().count() > 0){
                $urlRouterProvider.otherwise('main/homepage');
            }else{
                $urlRouterProvider.otherwise('login');
            }
        });

2.collections.js

export const LastLogin = new Ground.Collection('lastLogin', {connection: null});

In most of the cases, LastLogin.find().count() is 0, seldom will it be 1, in fact there are several records in lastLogin collection which can be correctly printed out after login page showed, that will be too late for me.

I tried enclosing the following code by Tracker.autorun

Tracker.autorun(function(){
    if(LastLogin.find().count() > 0){
        $urlRouterProvider.otherwise('main/home');
    }else{
        $urlRouterProvider.otherwise('login');
    }
});

but no help.

My final purpose is to get last user auto logged on, even in offline state. Any better solutions?

1

There are 1 answers

0
vdonkey On

Finally I worked it out by myself. The idea is ground:db has a "loaded" event which is documented here: https://github.com/GroundMeteor/db/blob/grounddb-caching-2016/EVENTS.md , I saw this doc days ago but didn't guess out the usage immediately.

The source(app.js):

// Startup
if (Meteor.isCordova) {
    angular.element(document).on('deviceready', onReady);
}else {
    angular.element(document).ready(onReady);
}

function onReady() {
    Ground.on('loaded', function (ret) {
        if(ret.collection == 'lastLogin'){
            angular.bootstrap(document, ['app']);
        }
    });
}