24 June 2019
Angular (11) -- Routing
by Jerry Zhang
Day 19: Angular Routing
Passing Query Parameters and Fragments
In template(routerLink)
In the url, we can also add a question mark with some parameters.
In the HTML file, if we want to go to a link with some parameters or hash sign, we can simply add queryparams
and
fragment
in the link.
<a
[routerLink]="['/servers', 5, 'edit']"
[queryParams]="{allowEdit: '1'}"
fragment="loading"
class="list-group-item"
*ngFor="let server of servers">
</a>
In Program
In the navigate method, we can add parameter, queryParams
, instead of relativeTo
as last time.
onLoadServer(id: number) {
this.router.navigate(['/servers', id, 'edit'], {queryParams: {allowEdit: '1'}, fragment: 'loading'});
}
The second parameter in the navigate method is just a javascript object where we can set any value.
In both of these two approaches, router link and programming, we can arrive the URL below:
localhost:4200/servers/1/edit?allowEdit=1#loading
Retrieving query parameters and fragments in URLs
Again, we need to inject the ActivatedRoute here.
constructor(private serversService: ServersService,
private route: ActivatedRoute) { }
Just as before, there are two ways to retrieve it.
- Use snapshot, not recommended
console.log(this.route.snapshot.queryParams);
console.log(this.route.snapshot.fragment);
- subscribe
this.route.queryParams.subscribe();
this.route.fragment.subscribe();
tips: parameter data type
When we get information from URLs, the parameters we get is of type string. So, we put a plus symbol to convert it to a number.
ngOnInit() {
const id = +this.route.snapshot.params['id'];
this.server = this.serversService.getServer(id);
this.route.params
.subscribe(
(params: Params) => {
this.server = this.serversService.getServer(+params['id']);
}
);
}