app/core/guards/queryGuard.guard.ts
Properties |
|
Methods |
constructor(pubService: PublicationService, router: Router, activatedRoute: ActivatedRoute)
|
||||||||||||
Defined in app/core/guards/queryGuard.guard.ts:6
|
||||||||||||
Parameters :
|
canActivate | |||||||||
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)
|
|||||||||
Defined in app/core/guards/queryGuard.guard.ts:18
|
|||||||||
Check that the necessary query parameters are present and that they have the correct value. If the parameters needs to be modified, we do so in the guard before navigating, and then redirect to the correct URL.
Parameters :
Returns :
boolean
|
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, ActivatedRoute } from '@angular/router';
import { PublicationService } from '../services/publication-service/publication.service';
@Injectable()
export class QueryGuard implements CanActivate {
constructor(
private pubService: PublicationService,
private router: Router,
public activatedRoute: ActivatedRoute
) {}
/**
* Check that the necessary query parameters are present and that they have the correct value.
* If the parameters needs to be modified, we do so in the guard before navigating, and then redirect to the correct URL.
*/
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const paramsObj = Object.assign({}, route.queryParams);
let modified = false;
const pubId = this.pubService.getPublicationId();
const siteLanguage = this.pubService.getLanguage();
// default * search to get all results
if (!('q' in paramsObj) || paramsObj.q.trim() === '' ) {
paramsObj['q'] = '*';
modified = true;
}
// Check if searcher is set. If not, check if on brand site and add prefix if so.
if (!('searcher' in paramsObj)) {
paramsObj['searcher'] = 'all';
modified = true;
}
if (!('site' in paramsObj) || paramsObj.site !== pubId) {
paramsObj['site'] = pubId;
modified = true;
}
if (!('language' in paramsObj) || paramsObj.language !== siteLanguage) {
paramsObj['language'] = siteLanguage;
modified = true;
}
// If we had to modify query params, navigate to new url. replaceUrl to replace previous wrong params in browser history.
if (modified) {
const url = state.url.split('?')[0];
this.router.navigate([url], {
queryParams: paramsObj,
replaceUrl: true
});
return false;
}
else { return true; }
}
}