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
}
I'm using the latest AWS-Amplify's authentication component. It can logged in successfully but after login I need to sent the route to another url which I can't able to achieve, it keeping the same url after logged in. BUT I need to set a custom url where it automatically redirect if a user login successfully.
Note : I'm not using aws-amplify-angular package I'm using these packages,
"#aws-amplify/ui-angular": "^2.4.4",
"aws-amplify": "^4.3.21",
Also I checked this import {AuthenticatorService} from '#aws-amplify/ui-angular'; service but here I didn't find any response with observable type, I think that's why I don't get any event or something instantly after user login successfully. I need to route imminently after a successful login. So I need an event so that I can do that .
My main.ts :
import { Amplify } from 'aws-amplify'
import awsmobile from './aws-exports'
Amplify.configure(awsmobile)
auth.component.html : [ there is no code in ts ]
<amplify-authenticator [signUpAttributes]="['email']"></amplify-authenticator>
& the routes setup like this,
const routes: Routes = [
{
path: 'home',
component: HomeComponent,
canActivate: [AuthGuard]
},
{
path: 'auth',
component: AuthComponent
},
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
}
];
I didn't get any good solution with using this packages. Please help with this issue or am I missed something in my configuration .
I didn't want to use aws-amplify-angular package but I need to because there is no good solution out there, without this package I tried to use angular hooks because when change detection runs I can get authenticated & unauthenticated states from AuthenticatorService which came from import { AuthenticatorService } from '#aws-amplify/ui-angular'; but using hooks (AfterContentChecked, AfterViewChecked) it works sometimes,sometimes not & sometimes occurred errors.
[ I did't use both hooks at a time, I tried separately]
So, Finally I need to install aws-amplify-angular for using the AmplifyService's & then I do this changes bellow,
constructor(private router: Router, private amplifyService: AmplifyService) { }
ngOnInit() {
this.amplifyService.authStateChange$.subscribe(({state, user}) => {
if (state === 'signedIn') {
this.router.navigate(['/home'])
}
})
}
Don't forget to add AmplifyService to put in providers array in app.module.ts.
In the AuthenticatorService import of the latest version of #aws-amplify/ui-angular, you can subscribe and listen for authStatus which is authenticated, deauthenticated and configured, if you listen from ngOnInit or from the constructor you can wait for the necessary status to do redirection.
It also works for the signOut
constructor(public amplifyService: AuthenticatorService, public router: Router) {
this.amplifyService = amplifyService;
amplifyService.subscribe((data: any) => {
if (data.authStatus === "authenticated") {
this.router.navigate(['/home']);
};
})
}
ngOnInit(): void {
}
to make signOut you just have to use this function in your navbar
logOut() {
this.amplifyService.signOut()
this.router.navigate(['/login']);
}
This way you can maintain the latest version of aws-amplify packages and not get errors or failures from compiling outdated packages or packages that conflict with other aws packages.
import { Hub } from 'aws-amplify';
ngOnInit() {
// Used for listening to login events
Hub.listen('auth', ({ payload: { event, data } }) => {
if (event === 'signIn') {
const { signInUserSession = {} } = data;
const { accessToken = {} } = signInUserSession;
const { jwtToken, payload = {} } = accessToken;
const { 'cognito:groups': roles, username, exp } = payload;
localStorage.setItem('accessToken', jwtToken);
const payloadToSave = {
Role: roles[0],
Username: username,
exp,
};
localStorage.setItem('payload', JSON.stringify(payloadToSave));
this.zone.run(() => this.router.navigate(['/dashboard']));
} else {
console.log('Hide loader');
}
});
//currentAuthenticatedUser: when user comes to login page again
Auth.currentAuthenticatedUser()
.then(() => {
this.router.navigate(['/dashboard'], { replaceUrl: true });
})
.catch(err => {
console.log(err);
});
}
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
im trying to inject a service (LoggingService) into another service (AccountService) so accountsService definitely need #Injectable to inject it proberly..... the problem is i have just add it to the constructor without adding #Injectable and it's working as it should ....... how can my app run though without using #Injectable?
import { LoggingService } from "./logging.service";
export class AccountsService {
constructor(private loggingService: LoggingService) {}
accounts = [{
name: 'Master Account',
status: 'active'
},
{
name: 'Testaccount',
status: 'inactive'
},
{
name: 'Hidden Account',
status: 'unknown'
}
];
addAccount(newAccount: {name: string, status: string}) {
this.accounts.push(newAccount);
this.loggingService.loggingStatusChange(newAccount.status);
}
updateStatus(id: number, status: string) {
this.accounts[id].status = status;
this.loggingService.loggingStatusChange(status);
}
}
As long as you are not inject or use AccountsService to any component visible by your app, it will work just fine ( what i mean by saying visible is that it been whether 'imported / declared / provided' in the #NgModule() class decorator).
If you already used your AccountsService somewhere and your app not yelling error at you. Then it probably provided in the #NgModule({}) somewhere in your app. Otherwise there no way it can work.
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');
}
});
}