Access dynamic URL param in angular 6 - javascript

In my angular 7 code I'm trying to fetch the clientId passed in the URL. clientId will be dynamic.
localhost:4200/client/xyz
app.routing.ts
{
path: 'client/:clientId',
component: AppComponent
},
app.component.ts
constructor(private route: ActivatedRoute) { }
ngOnInit() {
console.log(this.route.snapshot.paramMap.get('clientId'));
});
It prints null in the console

You can get the route params using this method
this.route.params.subsribe(params => {
console.log(params['clientId'])
});
or
this.activateRoute.snapshot.params['clientId']
PLease let me know if you still have problem

Use params instead of paramMap,
console.log(this.route.snapshot.params['clientId']);

Related

how can I make an a tag with a routerLink force a reload of that route?

I have routes defined like:
[
{
path: '',
component: MyComponent,
},
{
path ':id',
component: MyComponent,
},
...
So I can go to /foo or /foo/123
The component knows to fetch that specific id or to fetch a collection of all records whether or not the id parameter exists..
The problem is, I have a link that does:
<a routerLink="/foo">foo!</a>
If I type into the url bar /foo I see the list of records, and if I type /foo/123 it also works correctly and loads that specific record. However, if I am on /foo/123 and then click that link I see the url change to /foo but it does nothing, does not re-render the component, so the it is still showing the 123 record, rather than the list of records as it should...
How can I force it to do a reload?
I tried putting runGuardsAndResolvers: 'always' in the route, I also tried {onSameUrlNavigation: ‘reload’} on the app level forRoot route config options, and also tried the incredibly dumb hack I've seen multiple people talk about with adding a queryParam of a timestamp on the <a> tag... None of those things worked.
You can do it by subscribing to the route params, and whenever it emits the new value, you can re-initialize your component data.
import { ActivatedRoute } from '#angular/router';
import { Subscription } from 'rxjs';
...
private subs: Subscription[] = [];
constructor(private route: ActivatedRoute) {}
ngOnInit(): void {
this.subs.push(
this.route.params.subscribe({
next: (response) => {
const id = response['id'];
this.initializeData();
},
error: (errorResponse) => {
console.log('ERROR: ', errorResponse);
},
})
);
}
ngOnDestroy() {
this.subs.forEach((s) => s?.unsubscribe());
}
initializeData() {
// Do something
}

Unable to fetch dynamic queryParams without reloading the page [duplicate]

I am trying to update (add, remove) queryParams from a component. In angularJS, it used to be possible thanks to :
$location.search('f', 'filters[]'); // setter
$location.search()['filters[]']; // getter
I have an app with a list that the user can filter, order, etc and I would like to set in the queryParams of the url all the filters activated so he can copy/paste the url or share it with someone else.
However, I don't want my page to be reloaded each time a filter is selected.
Is this doable with the new router?
You can navigate to the current route with new query params, which will not reload your page, but will update query params.
Something like (in the component):
import {ActivatedRoute, Router} from '#angular/router';
constructor(
private router: Router,
private activatedRoute: ActivatedRoute,
) { }
public myMethodChangingQueryParams() {
const queryParams: Params = { myParam: 'myNewValue' };
this.router.navigate(
[],
{
relativeTo: activatedRoute,
queryParams: queryParams,
queryParamsHandling: 'merge', // remove to replace all query params by provided
});
}
Note, that whereas it won't reload the page, it will push a new entry to the browser's history. If you want to replace it in the history instead of adding new value there, you could use { queryParams: queryParams, replaceUrl: true }.
EDIT:
As already pointed out in the comments, [] and the relativeTo property was missing in my original example, so it could have changed the route as well, not just query params. The proper this.router.navigate usage will be in this case:
this.router.navigate(
[],
{
relativeTo: this.activatedRoute,
queryParams: { myParam: 'myNewValue' },
queryParamsHandling: 'merge'
});
Setting the new parameter value to null will remove the param from the URL.
#Radosław Roszkowiak's answer is almost right except that relativeTo: this.route is required as below:
constructor(
private router: Router,
private route: ActivatedRoute,
) {}
changeQuery() {
this.router.navigate(['.'], { relativeTo: this.route, queryParams: { ... }});
}
In Angular 5 you can easily obtain and modify a copy of the urlTree by parsing the current url. This will include query params and fragments.
let urlTree = this.router.parseUrl(this.router.url);
urlTree.queryParams['newParamKey'] = 'newValue';
this.router.navigateByUrl(urlTree);
The "correct way" to modify a query parameter is probably with the
createUrlTree like below which creates a new UrlTree from the current while letting us modify it using NavigationExtras.
import { Router } from '#angular/router';
constructor(private router: Router) { }
appendAQueryParam() {
const urlTree = this.router.createUrlTree([], {
queryParams: { newParamKey: 'newValue' },
queryParamsHandling: "merge",
preserveFragment: true });
this.router.navigateByUrl(urlTree);
}
In order to remove a query parameter this way you can set it to undefined or null.
The answer with most vote partially worked for me. The browser url stayed the same but my routerLinkActive was not longer working after navigation.
My solution was to use lotation.go:
import { Component } from "#angular/core";
import { Location } from "#angular/common";
import { HttpParams } from "#angular/common/http";
export class whateverComponent {
constructor(private readonly location: Location, private readonly router: Router) {}
addQueryString() {
const params = new HttpParams();
params.append("param1", "value1");
params.append("param2", "value2");
this.location.go(this.router.url.split("?")[0], params.toString());
}
}
I used HttpParams to build the query string since I was already using it to send information with httpClient. but you can just build it yourself.
and the this._router.url.split("?")[0], is to remove all previous query string from current url.
Try
this.router.navigate([], {
queryParams: {
query: value
}
});
will work for same route navigation other than single quotes.
If you want to change query params without change the route. see below
example might help you:
current route is : /search
& Target route is(without reload page) : /search?query=love
submit(value: string) {
this.router.navigate( ['.'], { queryParams: { query: value } })
.then(_ => this.search(q));
}
search(keyword:any) {
//do some activity using }
please note : you can use this.router.navigate( ['search'] instead of this.router.navigate( ['.']
I ended up combining urlTree with location.go
const urlTree = this.router.createUrlTree([], {
relativeTo: this.route,
queryParams: {
newParam: myNewParam,
},
queryParamsHandling: 'merge',
});
this.location.go(urlTree.toString());
Not sure if toString can cause problems, but unfortunately location.go, seems to be string based.
Better yet - just HTML:
<a [routerLink]="[]" [queryParams]="{key: 'value'}">Your Query Params Link</a>
Note the empty array instead of just doing routerLink="" or [routerLink]="''"
First, we need to import the router module from angular router and declare its alias name
import { Router } from '#angular/router'; ---> import
class AbcComponent implements OnInit(){
constructor(
private router: Router ---> decalre alias name
) { }
}
1. You can change query params by using "router.navigate" function and pass the query parameters
this.router.navigate([], { queryParams: {_id: "abc", day: "1", name: "dfd"}
});
It will update query params in the current i.e activated route
The below will redirect to abc page with _id, day
and name as query params
this.router.navigate(['/abc'], { queryParams: {_id: "abc", day: "1", name:
"dfd"}
});
It will update query params in the "abc" route along with three query paramters
For fetching query params:-
import { ActivatedRoute } from '#angular/router'; //import activated routed
export class ABC implements OnInit {
constructor(
private route: ActivatedRoute //declare its alias name
) {}
ngOnInit(){
console.log(this.route.snapshot.queryParamMap.get('_id')); //this will fetch the query params
}
Angular's Location service should be used when interacting with the browser's URL and not for routing. Thats why we want to use Location service.
Angulars HttpParams are used to create query params. Remember HttpParams are immutable, meaning it has to be chained when creating the values.
At last, using this._location.replaceState to change to URL without reloading the page/route and native js location.path to get the url without params to reset the params every time.
constructor(
private _location: Location,
) {}
...
updateURLWithNewParamsWithoutReloading() {
const params = new HttpParams().appendAll({
price: 100,
product: 'bag'
});
this._location.replaceState(
location.pathname,
params.toString()
);
}
I've had an interesting situation where we used only one component for all routes we had. This is what routes looked like:
const routes: Routes = [
{
path: '',
component: HomeComponent,
children: [
{ path: 'companies', component: HomeComponent },
{ path: 'pipeline', component: HomeComponent },
// ...
]
},
// ...
];
So, basically, paths /, /companies and /pipeline were all having the same component that had to be loaded. And, since Angular prevents reloading of the components if they were previously loaded in the DOM, Router's navigate method returned a Promise that always resolved with null.
To avoid this, I had to use onSameUrlNavigation. By setting this value to 'reload', I managed to make the router navigate to the same URL with the updated query string parameters:
#NgModule({
imports: [RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload' })],
exports: [RouterModule]
})
Also you can add BehaviorSubject like:
refresher$ = new BehaviorSubject(null);
I changed my code from that:
this.route.queryParamMap.subscribe(some code)
to:
combineLatest([
this.route.queryParamMap,
this.refresher$
])
.pipe(
map((data) => data[0])
)
.subscribe(here is your the same code)
And when you need refresh your subscription, you need call this:
this.refresher$.next(null);
Also don't forget add unsubscribe from that to ngOnDestroy

Angular 9 : Allow trailing slash with optional parameter value in routes

We have below requirement for optional parameter. Routing is not matching with current URL. There are different cases of Parameter value. Parameter value can be blank. What we can change in below routing code?
Below are the request URL cases.
http://localhost:4200/act/sso/app/2040/token/7d2f-4ddd-924f-3fd36572/address/chd/city/chd/state/chd/zip/94524/tax/1000/rep1/ianchi/rep1Email/ianchi#am.com/rep2/Ryan/rep2Email/raphael#am.com
http://localhost:4200/act/sso/app/2040/token/7d2f-4ddd-924f-3fd36572/address/pkl/city/phonix/state/ca/zip/90401/tax/600/rep1//rep1Email//rep2//rep2Email/
http://localhost:4200/act/sso/app/2040/token/7d2f-4ddd-924f-3fd36572/address//city//state//zip//tax//rep1/ianchi/rep1Email/ianchi#am.com/rep2/Ryan/rep2Email/raphael#am.com
I am using below code in app-routing.module.ts file.
{
path: 'act/sso/app/:app/token/:token/address/:address/city/:city/state/:state/zip/:zip/tax/:tax/rep1/:rep1/rep1Email/:rep1Email/rep2/:rep2/rep2Email/:rep2Email',
component: SSOComponent
},
Please help on this?
Parameter value can be blank
If that would be the case, use Angular's Query Parameters instead of Router Parameters -- With that, you need to send an object inside the URL which Angular will parse in.
Attached Stackblitz Demo for your reference
Route
{
path: 'sso',
component: SSOComponent
},
Template from another component
<a [routerLink]="sso"
[queryParams]="ssoParams">SSO</a>
or inside it's component
#Component({...})
export class OtherComponent {
ssoParams = {
app: 1,
token: 123,
address: 'random'
}
constructor(private router: Router) {}
// or you can also redirect it inside the component
redirect(): void {
this.router.navigate(['sso'], { queryParams: this.ssoParams })
}
}
When redirected, the url will now be:
/sso?app=1&token=123&address=random
If it's empty or if you have passed an empty value on those objects, the URL which angular will parse in will only turn to like this, which is still valid:
/sso?app=&token=&address=
SSO Component
#Component({...})
export class SSOComponent {
constructor(private route: ActivatedRoute) {}
ngOnInit(): void {
// fetch the query parameters via subscribe
this.route.queryParams.subscribe(params => console.log(params))
// or to fetch the query parameters directly via object
// which this will contain: {app: 1, token: 123, address: 'random'}
console.log(this.route.snapshot.queryParams);
}
}

Inject store into errorhandler class Angular

I am trying to implement sentry error handling into my application, now I have it set up and working as expected.. but now I want to be able to pass user information on the Sentry object for better error logging.
So I have the following setup
export class SentryErrorHandler implements ErrorHandler {
userInfo: UserInfo;
constructor(
private _store: Store<AppState>
) {
this.getUserInfo();
}
getUserInfo() {
this._store.select('userInfo')
.subscribe(result => {
this.userInfo = result;
});
}
handleError(err: any): void {
Sentry.configureScope((scope) => {
scope.setUser({
email: this.userInfo?.emailAddress,
id: this.userInfo?.id?,
});
});
const eventId = Sentry.captureException(err.originalError || err);
Sentry.showReportDialog({ eventId });
}
}
and I am providing the error handler like so in my root module
// ...
{ provide: ErrorHandler, useClass: SentryErrorHandler }
// ...
but what happens is, when I start my application I get the following error
Obviously im doing something wrong here, any help would be appreciated!
This error is happening because without the #Injectable decorator Angular cannot wire up dependencies for the class (even using it in providers).
So all you have to do is add the #Injectable() decorator in your error class.
See a demo here:
https://stackblitz.com/edit/angular-ctutia

How to direct to a page on the basis of response Angular 6

I have two pages on my UI and i want to redirect the USER on the basis of HTTP response. PFB code .
{
"routerName": this.routerName,
"serviceId" : this.serviceId,
"serviceType" : ILL
}
Now my servicetype is ILL then i want to direct the page to ILL page and when the value service type is GVPN then i want to direct it to GVPN page.
PFB routerModule
RouterModule.forRoot([
{ path: 'ill' , component: IpIllComponent }, // Want to go to this page when service type is ILL
{ path: 'gvpn' , component: IpGvpnComponent } // Want to go to this page when service type is GVPN
])
Please help me on this.
You need to inject the router in your class and then use it to navigate:
constructor(private router: Router) {}
const path = response.serviceType === 'ILL'? 'ill' : 'gvpn';
this.router.navigate([path])
See docs: https://angular.io/guide/router
In runtime you can check the service type and then use router.navigate to navigate to a page which you want.
if (serviceType === 'ILL')
this.router.navigate(['/ill'])
else
this.router.navigate(['/gvpn']);
constructor(private router: Router) {}
this.router.navigate(['/gvpn']);
Please follow this angular documentation. You will be find all your issue related to Angular routing.
angular routing
constructor(private router: Router, private http: HttpClient) {}
RouteByServiceResponse() {
this.http.get(<url>).subscribe(response =>
if ( response.serviceType === 'ILL' )
{
this.router.navigateByUrl('/ill');
} else if ( response.serviceType === 'GVPN' ) {
this.router.navigateByUrl('/gvpn');
}
});
}

Categories