I have an encoded URL parameter that I need to decode when the app initializes. I need to do this in a provider because that object needs to be available to routing guards as well as components.
I have the following provider. It grabs the incoming query parameter and parses it into an interface.
import { Injectable } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { MyObject } from './data.d';
@Injectable()
export class DataProvider {
constructor(private route: ActivatedRoute) { }
public get() {
debugger;
this.route.queryParams.subscribe(params => {
let payload = params['data'] !== undefined ? Base64.decode(params['data']) : null;
return payload ? <MyObject>JSON.parse(payload) : null;
});
}
}
I'm having trouble with the syntax on how to add this to my provider array, and how to access it from other places in the app (specifically routing guards). What's the correct way to set this up?
EDIT: It seems that perhaps query parameters aren't available at the time the provider is initialized. Where can I parse the query param in a place other than the component? I need to be able to access it in the routing guard.
app.guard.ts:
import { Injectable } from '@angular/core';
import { Router, RouterStateSnapshot, ActivatedRouteSnapshot, CanActivate } from '@angular/router';
import { SessionService } from './services/session.service';
import { DataProvider } from './data.provider';
@Injectable()
export class SessionIsValidGuard implements CanActivate {
constructor(
private router: Router, private sessionService: SessionService, private dataProvider: DataProvider
) {}
/*
* Main guard to verify that session ID is valid before proceeding
*/
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
// When the below is called, dataProvider.get() returns null
let params = this.dataProvider.get();
if (this.sessionService.isValidSessionId(params.transactionId)) {
return true;
} else {
this.router.navigate(['/error', { error: 'Invalid session' }]);
}
}
}
app.component.ts:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { DataProvider } from './data.provider';
/*
* Main app component that houses all views.
*/
@Component({
selector: 'app-comp',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
constructor(private router: Router, private route: ActivatedRoute, private srcService: SRCService, private dataProvider: DataProvider) {}
ngOnInit() {
// Here dataProvider.get() returns the expected value
console.log(this.dataProvider.get());
}
}