Get the Query parameter from the URL in to Component - javascript

I am trying to understand how I can get the Query parameter from the URl in to my Component. Below is what I tried, I set the route in the app-routing.module.ts like
{
path: 'ProjectShipment/userId/231',
component: ProjectShipmentComponent,
data: { title: 'Project Shipment' },
}
And with in the project-shipment.component.ts I tried like
import {Router, ActivatedRoute, Params} from '#angular/router';
export class ProjectShipmentComponent implements OnInit {
constructor( private activatedRoute: ActivatedRoute) { }
ngOnInit() {
debugger;
this.activatedRoute.queryParams.subscribe(params => {
const userId = params['userId'];
console.log(userId);
});}}
When I debug it I get undefined in the logs
What am I missing here

You need to change your route to
{
path: 'ProjectShipment/:userId',
component: ProjectShipmentComponent,
data: { title: 'Project Shipment' },
}
Then when you call it like yourhost/projectshipment/231 in your component
this.activatedRoute.params.subscribe(params => {
const userId = params['userId'];
console.log(userId);
})
to get queryparams you code is right but your route should
{
path: 'ProjectShipment',
component: ProjectShipmentComponent,
data: { title: 'Project Shipment' },
}
and url should be yourhost/projectshipment?userid=231

Related

Load data first before AuthGuard called in Angular

I am currently implementing Auth guard in my routes. I want to load data first before auth guard being called. Currently I am doing this.
In my auth-guard.service.ts I have this.
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if ( this.authService.isLoggedIn() ) {
return true;
} else {
this.router.navigate(['login']);
return false;
}
}
And in my auth.service.ts
export class AuthService {
constructor() { }
isLoggedIn() {
return this.getUser() !== null;
}
setSession(userId: string) {
sessionStorage.setItem('userId', userId);
}
getUser() {
return sessionStorage.getItem('userId');
}
}
And in my routes I am calling Auth guard and DataResolver
const routes: Routes = [
{
path: '',
component: UserComponent,
canActivate: [AuthGuardService],
resolve: {
data: DataResolver
},
children: [
{
path: '',
redirectTo: 'dashboard',
pathMatch: 'full',
},
{
path: 'dashboard',
component: UserDashboardComponent,
data: {
breadcrumb: 'Dashboard',
},
}
]
]
DataResolver
#Injectable({
providedIn: 'root'
})
export class DataResolver {
constructor(private authService: AuthService,
private activatedRoute: ActivatedRoute) { }
resolve() {
this.activatedRoute.queryParams.subscribe((data) => {
const userId = data.userId;
if (userId) {
this.authService.setSession(userId);
}
});
}
}
Why it is still calling the auth guard first. What I want to to call the DataResolver first before the auth guard.

Send JSON from one component to another using routing and not display on URL?

I am trying to pass JSON on routing URL here is my
app.route.ts code
{path: 'calculator', component: CalculatorComponent,data : {some_data : null}},
and my code to route the data is
this.router.navigate(['/home/calculator', {some_data:this.loanData}]);
and the calculator.ts have the oninit method code is like this
import {ActivatedRoute} from '#angular/router';
constructor(private route: ActivatedRoute) {}
sub
ngOnInit() {
this.sub = this.route
.data
.subscribe(v => console.log(v));
}
output is like this
{"some_data":null}
the problem is it's not showing the json, I passed from the ts first component
Is there a reason you want to navigate by url why not use the navigate method like this:
in RouteConf: { path: '/path/:data', name: 'Defined_Path_Name', component: PathComponent }
navigate with: this.router.navigate(['Defined_Path_Name', { data: { entity: 'entity' } } ]);
in /path: console.log(this.routeParams.get('data'))
that got me: Object {entity: "entity"}
//in your route file
in RouteConf: {path: 'calculator/:data', component: CalculatorComponent},
//in your component file navigate by like below
navigate with: this.router.navigate(['/calculator', { data: this.loaddata } ]);
//and get data in /calculator path like
this.data = this.route.snapshot.data['data'];
than console.log(this.data);
Can you try using this, this should work, hope so
app.route.ts code
{path: 'calculator', component: CalculatorComponent},
and your code to route
let someData = {
this.loanData
};
this.router.navigate(['/home/calculator/'+someData]);
and the calculator.ts have the oninit method code is like this
import {ActivatedRoute} from '#angular/router';
constructor(private route: ActivatedRoute) {}
sub
ngOnInit() {
this.route.params
.subscribe(data => {
this.sub = data;
console.log(this.sub);
});
}

Resolving data in angular 2

Introduction:
I have a search-box that let's you select a tv show, which then logs the title of the show you clicked, as well as the id for that show. I define this in my:
landingpage.component
<li (click)="selectShow(list.title)" [routerLink]="['/details', list.id]"
*ngFor="let list of shows"> {{list.show}} </li>
When a li is clicked, it sends the list.id as a parameter to my /details component. selectShow just logs the name (list.title) of the show that was clicked.
My problem:
I cannot seem to figure out how to resolve my list.title value, so that it appears in my /details route in this.route.snapshot.data['title']
My code:
app.routing.module.ts
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { TitleResolver } from './services/title.service';
const routes: Routes = [
{ path: '', component: LandingPage },
{
path: 'details/:id', component: ResultPage,
resolve: {
title: TitleResolver //hopefully contains 'title' data here?
}
}
}
];
resultpage.component.ts
title; //variable we will assign to title
constructor(private route: ActivatedRoute) {}
this.route.data
.subscribe((data: { title: Title}) => {
console.log(title);
});
title.service.ts
// this gives us the name of the clicked show
class ShowService {
fetchTitle(title) {
return title;
}
}
#Injectable()
export class TitleResolver {
constructor(private showservice: ShowService) { }
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<any> | Promise<any> | any {
return this.showservice.fetchTitle(route.params.title);
}
}
My question
What are the intermediate step(s) that I need to do in order to send the selected list.title value from my landingpage.component data to my app.routing.module.ts, so that I can receive it in my resultpage.component ?

Angular router get child param from root component

I have this structure in my app.component.html:
<app-main-nav></app-main-nav>
<router-outlet></router-outlet>
This is my routes:
const routes = [
{path: "", redirectTo: "home", pathMatch: "full"},
{
path: "posts", component: PostsComponent,
children: [{
path: ":id",
component: PostComponent
}];
}
]
I am trying to access the params from the PostComponent page in my MaiNavComponent but it throws an error.
export class MainNavComponent implements OnInit {
constructor( private route: ActivatedRoute) {
route.params.subscribe(console.log)
}
}
How can I get the :id of the PostComponent from the MainNavComponent?
I tried to do this:
route.params.subscribe(console.log)
Here I get an empty object.
And this:
route.firstChild.params.subscribe(console.log)
Cannot read property 'params' of null
The problem is that ActivatedRoute only available inside components loaded in an outlet (route-outlet). In the outer components you can inject the router and use it as follow:
export class MainNavComponent implements OnInit {
constructor(private router: Router) {}
ngOnInit() {
// Fires when the url changes
this.router.events.subscribe(data => {
// Only handle final active route
if (data instanceof NavigationEnd) {
// parsedUrl conatins params, queryParams
// and fragments for the active route
let parsedUrl = this.router.parseUrl(this.router.url);
console.log(parsedUrl);
}
});
}
}
I hope this will help you.
constructor(
private router: Router,
private activatedRoute: ActivatedRoute) {
}
ngOnInit() {
this.loadParams();
}
private loadParams(): void {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
let activatedRoute = this.activatedRoute.firstChild;
while (!activatedRoute) {
activatedRoute = activatedRoute.firstChild;
}
const value = activatedRoute.snapshot.paramMap.get('parmeter key');
}
});
}
You have to snapshot to get ID from the URL.Uodate constructor with below
constructor( private route: ActivatedRoute) {
}
ngOnInit() {
// (+) converts string 'id' to a number
let id = +this.route.snapshot.params['id'];
}

Angular 2, How to display current route name? (router 3.0.0-beta.1)

I want to display the name of the route in the app.component.html template. I'm looking for a simple solution, something that can be written like this:
{{router.currentRoute.name}}
My current router config:
export const routes: RouterConfig = [
{
path: '',
redirectTo: '/catalog',
pathMatch: 'full'
},
{
path: 'catalog',
name: 'Catalog', // Is this property deprecated?
component: CatalogComponent
},
{
path: 'summary',
name: 'Summary',
component: SummaryComponent
}
];
If your routes are configured with your route name in the data property like this:
{
path: 'somepath',
component: SomeComponent,
data: {
name: 'My Route Name'
}
}
In your app.component.ts you can import 'rxjs/add/operator/filter'; + import { ActivatedRoute, Router, NavigationEnd } from '#angular/router'; and do the following:
constructor(
private route: ActivatedRoute,
private router: Router
) { }
ngOnInit() {
this.router.events
.filter(event => event instanceof NavigationEnd)
.subscribe(event => {
let currentRoute = this.route.root;
while (currentRoute.children[0] !== undefined) {
currentRoute = currentRoute.children[0];
}
console.log(currentRoute.snapshot.data);
})
}
This will listen for NavigationEnd events and then traverse down to the current route so that you can access the data of that route.
If you are on /somepage using the code above, it should print { name="My Route Name"} in your console.
constructor(
private route: ActivatedRoute,
private router: Router
) { }
ngOnInit() {
this.router.events.pipe(
.filter(event => event instanceof NavigationEnd)).subscribe(event => {
let currentRoute = this.route.root;
while (currentRoute.children[0] !== undefined) {
currentRoute = currentRoute.children[0];
}
console.log(currentRoute.snapshot.data);
});
}```
try this if anybody facing issue with filter

Categories

Resources