Search Lessons, Code Snippets, and Videos
search by algolia
X
#native_cta# #native_desc# Sponsored by #native_company#

Query Firebase Data With Angular Router URL Parameters

written by Jeff Delaney
full courses for pro members

This snippet shows you how to use the Angular Router to make queries to the Firebase Realtime Database. It works by subscribing to the ActivatedRoute, then using the params to make a query to Firebase with AngularFire2.

Structure Routes with URL Params

Adding variable URL params to an Angular route is simple. Just prefix it with a colon, such as :someId.

app.routing.module.ts

const routes: Routes = [
{ path: 'posts', component: PostsListComponent },
{ path: 'posts/:postId', component: PostObjectComponent, },
];

In the list component, we will iterate of some records and use their $key property in the URL as the :postId param.

At this point, let’s assume our user has navigated to https://example.com/posts.

post-list.ts

posts: any;

constructor(private db: AngularFireDatabase) { }

ngOnInit() {
this.posts = this.db.list('/posts')
}

post-list.html

<div *ngFor="let post of posts | async">

<a [routerLink]="post.$key">{{ post.title }} Link</a>

</div>

Make Queries with a FirebaseObjectObservable

When the user navigates to a given post, we can subscribe the params and make the query to Firebase as a FirebaseObjectObservable.

After clicking a link, the user will be at a route the looks like https://example.com/posts/-KsOzIPzSZ4FXU06YdOw.

post-object.ts

post: any

constructor(private route: ActivatedRoute) {}

ngOnInit() {
this.route.params.subscribe(params => {
this.post = this.db.object('/posts/' + params['postId'])
});
}

post-object.html

Then you have the post object available as an Observable to unwrap in the HTML.

{{ post | async | json }}