Angular-meteor how to rerun html with router

I have a Notifications collection and i subscribe to that collection on my home page.

this.autorun(() => {
    this.subscribe('notifications', () =>{
        this.ngZone.run(() => {
            this.notifications = Notifications.find({});
        });
    }, true);
});

On another page (Notifications) i try to filter through the same collection (without subscribing to it). Problem is on that Notification page when i try to display the data from notification to HTML it does
not display anything even though there is the data. I can see that page loads the data and then somehow it is gone very very quickly. I tried using everything like Tracker, NgZone; nothing is working. I even put a div around HTML to check and display template only if Notifications
exists (*ngIf=“notifications”).

Weird thing is if i insert NotificationComponent into HomeComponent and use it into Home HTML it works. Any ideas?

I can only speculate without seeing your code, but this is what I think is happening. I’m assuming that you’re using angular-ui-router.

In Angular-Meteor, all of your subscriptions are directly linked to the scope of your controller when you call this.subscribe(). Unless you are using some kind of UI framework that caches your views, such as Ionic, your scope will be destroyed when you navigate out of that route. When you navigate from your home page to your notifications page, the “Home” scope is destroyed and the subscription handle is automatically stopped.

The reason why you see that data on your Notifications page for a moment is because the previous route doesn’t get destroyed until you have already entered into the new route.

So, the solution is simply to subscribe to your notifications publication in the Notification page. This is following in line with subscription best-practices, which is to keep your subs as close as possible to the UI components.

One quick tip: Install Mongol. It’s an invaluable tool for debugging your collections and publications while developing.

Thanks a lot for your answer. Everything makes sense after your explanation. I was worried if i should Re-subscribe or not.

Will it be better if i subscribe in a Service and inject that service into 2 different components and get the data.

I’ve never tried using subscriptions within services, so I’m not sure how that will turn out. It could work well, but you’d have to try it out for yourself. Subscribing directly in the controller’s constructor seems simpler to me, but I’m definitely not an expert with Angular.

One other thing of note, if you subscribe to a publication in a parent route, its children will have that subscription data available to them. For example, if you have these routes and associated controllers:

app
app.home
app.notifications

both Home and Notifications will be able to access any subscribed data from App in their helpers.