Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 37 ยท Navigation and Routing

Ionic Route Params, Guards and Page Lifecycle

Pass data between Ionic pages with route and query params, protect routes with guards, and use ionViewWillEnter and friends because pages stay alive.

Because Ionic keeps pages alive in a stack, two things behave differently from a typical web app: when your code runs, and how data reaches a page. This lesson covers passing data through the URL, protecting pages with guards, and the Ionic lifecycle events that fire when a page enters or leaves view. Getting these right prevents the most common "my page shows old data" bug.

Passing data with route parameters

Route params identify which thing to show (/details/42). Query params carry optional options (/search?q=js&sort=new).

TypeScript
// Angular
constructor(private route: ActivatedRoute) {}
ngOnInit() {
  this.id = this.route.snapshot.paramMap.get('id');
  this.q = this.route.snapshot.queryParamMap.get('q');
}
JSX
// React (React Router v5)
const { id } = useParams();
const { search } = useLocation();
const q = new URLSearchParams(search).get('q');
TypeScript
// Vue
const route = useRoute();
const id = route.params.id;
const q = route.query.q;

Rules of thumb:

  • Put the id, not the object, in the URL, then load the object from your data layer. URLs must survive a refresh and be shareable.
  • Never put secrets in URLs.
  • For large or temporary objects (a selected file), use a shared service or store; Angular also supports state passed with navigation, but it is lost on refresh.

Stand-in: parse a route and query string

The matching logic behind params is simple. This stand-in matches /details/:id-style patterns and parses query strings. It is a simplified version of what routers do and runs in Node or the browser.

JS Stand-in: match route patterns and queries

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Guards

A guard runs before a route activates and can allow it, block it or redirect. Typical uses: require login, check a role, ask before leaving a form with unsaved changes.

TypeScript
// Angular functional guard
export const authGuard: CanActivateFn = () => {
  const auth = inject(AuthService);
  const router = inject(Router);
  return auth.isLoggedIn() ? true : router.createUrlTree(['/login']);
};

{ path: 'account', canActivate: [authGuard], loadComponent: ... }
TypeScript
// Vue
router.beforeEach((to) => {
  if (to.meta.requiresAuth && !auth.isLoggedIn) return '/login';
});
JSX
// React: a wrapper route
const PrivateRoute = ({ component: C, ...rest }) => (
  <Route {...rest} render={(p) => (auth.isLoggedIn ? <C {...p} /> : <Redirect to="/login" />)} />
);

Important: guards only protect the screen. Anyone can read your JavaScript, so the server must still verify every API request with a token and permissions. A guard is user experience, not security.

This runnable stand-in models a guard chain: each guard returns true or a redirect, and the first non-true result wins.

JS Stand-in: a guard chain

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The page lifecycle

Frameworks have their own lifecycle: Angular ngOnInit, React useEffect, Vue onMounted. These run once when the component is created. But in Ionic's stack, going to a detail page and back does not destroy the list page, so ngOnInit does not run again. Data refreshes therefore need Ionic's lifecycle events:

Event Fires Use it for
ionViewWillEnter Before the page becomes visible, every time Refresh data
ionViewDidEnter After the transition finishes Start animations, focus a field
ionViewWillLeave Before the page starts leaving Save drafts
ionViewDidLeave After it has left Stop timers and listeners
flowchart LR
  A["Created (ngOnInit)"] --> B["ionViewWillEnter"]
  B --> C["ionViewDidEnter"]
  C --> D["ionViewWillLeave"]
  D --> E["ionViewDidLeave"]
  E -->|"visit again"| B
  E -->|"popped"| F["Destroyed"]

Created once, entered many times.

How to use them:

TypeScript
// Angular
ionViewWillEnter() { this.loadNotes(); }
JSX
// React
import { useIonViewWillEnter, useIonViewDidLeave } from '@ionic/react';
useIonViewWillEnter(() => { loadNotes(); });
useIonViewDidLeave(() => { stopTimer(); });
TypeScript
// Vue
import { onIonViewWillEnter } from '@ionic/vue';
onIonViewWillEnter(() => loadNotes());

Stand-in: created once, entered many times

The following simulates a page controller to show why ngOnInit alone leaves stale data:

JS Stand-in: init once, enter many times

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Leaving with unsaved changes

A "can deactivate" guard asks before leaving a dirty form, and you can also use the lifecycle to save a draft in ionViewWillLeave. On mobile, a draft saved automatically is friendlier than a confirmation dialog. You will build forms next in Ionic form controls.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use ionViewWillEnter to reload data?

    Going back to a page that remained in the stack does not recreate it, so framework creation hooks do not run again.
  2. 2. What should a route /details/:id carry?

    IDs survive refresh and can be shared; objects and secrets do not belong in URLs.
  3. 3. Do route guards provide real security?

    Client code can be read and altered; the server is the only trusted enforcer.
  4. 4. Which event is best for stopping a timer when leaving?

    ionViewDidLeave runs after the page is no longer visible.

Summary

  • Route params identify the resource; query params carry options.
  • Guards redirect or block navigation but are not security.
  • Pages stay alive, so use ionViewWillEnter (or the hook equivalents) to refresh data.
  • Use ionViewDidLeave to stop work and ionViewWillLeave to save drafts.

Next: Ionic Form Controls