Getting the ID parameter

Here's how we can retrieve it:

import { Component } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";

@Component({
selector: "quiz",
templateUrl: './quiz.component.html',
styleUrls: ['./quiz.component.css']
})

export class QuizComponent {
quiz: Quiz;

constructor(private activatedRoute: ActivatedRoute,
private router: Router
) {

// create an empty object from the Quiz interface
this.quiz = <Quiz>{};

var id = +this.activatedRoute.snapshot.params["id"];
console.log(id);
if (id) {
// TO-DO: load the quiz using server- side API
}
else {
console.log("Invalid id: routing back to home...");
this.router.navigate(["home"]);
}
}
}

What we did here is quite simple to explain:

  • In line 2, we added a reference to the ActivatedRoute interface and to the Router class, so we can use both of them later on; the former will give us information about the currently active route, which will contain the GET parameter that we need to retrieve; the latter will allow us to redirect the user to the HomeView in case of an error.
  • In lines 13-28, we implemented the constructor class, where we get the ID GET parameter from the active route using the ActivateRoute interface. If the ID is not null or empty, we load the quiz using server-side API (this is yet to be done, hence the to-do comment), otherwise we route the user back to the HomeView.
Note that we're already using the private access modifier for the constructor parameters, as we will most likely need to have them available through the whole class later on.

The usage of the injected ActivatedRoute object instance is somewhat cryptic, hence it deserves a brief explanation. As you may know, this is the place where we can find information about route parameters, query parameters, and URL fragments for the currently active route. In order to access the ID query parameter, we need to look into the params property, which happens to be an Observable object. This basically means that we will normally need to subscribe to it in the following way, just like we did with the get() method result of HttpClient:

this.activatedRoute.params.subscribe(
params => {
let id = +params['id'];
// do something with id
});

This will indeed work; however, we were able to retrieve the ID parameter using a smaller amount of code and avoiding Observable entirely thanks to the snapshot property, which returns a flatten representation of the currently active route. As a general rule of thumb, we can--and should--use the snapshot whenever we don’t need to actively monitor the Observable changes.

As we already mentioned once, Observables are one of the most interesting features introduced by Angular; we’ll definitely talk more about them later on.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.240.119