I have the following routes:
ReactDOM.render(
React.createElement(ReactRouter.Router, {history: ReactRouter.hashHistory},
React.createElement(ReactRouter.Route, {path: '/', component: AppController}),
React.createElement(ReactRouter.Route, {component: LayoutController},
React.createElement(ReactRouter.Route, {path: '/dashboard', component: DashboardController}),
React.createElement(ReactRouter.Route, {path: '/signout', component: UserSignoutController})
)
)
, document.getElementById('content'));
This is how I redirect the application flow:
ReactRouter.browserHistory.push('/dashboard');
It works, but if I open my application on another machine with a different url structure, and I have to change url paths, I also have to change every push argument.
Is there a way to redirect using route names instead of paths?
In older versions it was possible to navigate by name, but AFAIK it is no longer working. In my opinion what you should do is to configure the basename of the history for your different servers, i.e. the prefix of the route. Take into account that the final part of the URL, the one that is configured by react-router is fixed.
In order to specify the basename, you should pass a custom history to the router.
useRouterHistory(createBrowserHistory)({ basename })
Related
I'm new in Angular but I came from various frameworks that are relevant to the Backend such as Django, I note that Angular has the same nature as Django routing a bit regardless that it belongs to client-side so, so I'm familiar with routing confused around how Angular handles routing and use router-link in the template in Angular.
there is my problem:
export const routes: Routes = [
{path: 'login', component: LoginComponent, outlet: "login"},
{path: 'signup', component: RegisterComponent, outlet: "register"},
]
when I'm trying to move to the login page by the following statement:
<a [routerLink]="['', {outlets: {login: ['login']}}]" ariaCurrentWhenActive="page" routerLinkActive="active">Signin?</a>
what is happening is that the link looks like this link when it displaying it in the inspect element:
/app/(login:login//register:signup)
my current page is /app/(register:signup) and all I want to do is to move to: /app/(login:login)
first of all, I want to know how to move to my target.
second: I want to understand the router link nature in angular and how it works if it is possible.
Say I have 2 routes '/users' and /users/:id. First one renders UserListComponent and second UserViewComponent.
I want to re-render component when navigating from /users/1 to /users/2. And of course if I navigate from /users to /users/1 and vice versa.
But I DON'T want to re-render component if I navigate from /users/1?tab=contacts to /users/1?tab=accounts.
Is there a way to configure router like this for entire application?
--
Update:
I'm importing RouterModule in AppRoutingModule like this:
RouterModule.forRoot(routes, { relativeLinkResolution: 'legacy' })
I'm using Angular 12
The default behavior of the Angular router is to preserve the current component when the URL matches the current route.
This behavior can be changed by using the onSameUrlNavigation option:
Define what the router should do if it receives a navigation request
to the current URL. Default is ignore, which causes the router ignores
the navigation. This can disable features such as a "refresh" button.
Use this option to configure the behavior when navigating to the
current URL. Default is 'ignore'.
Unfortunately, this option is not fine-grained enough to allow reload for path params and ignore for query params.
So you have to subscribe both to the query params and the path params changes with something like this:
constructor(route: ActivatedRoute) { }
ngOnInit() {
this.renderLogic();
this.route.params.subscribe(() => this.renderLogic());
this.route.queryParams.subscribe(() => this.renderLogic());
}
renderLogic() {
// ...
}
As far as I know, #Guerric P is correct, you can't completely re-render the component selectively like this, at least not without some trickery like subscribing to each event and then possibly blocking it for one scenario and not the other. Feel free to try something like that, but below is an alternative if you make use of resolvers to fetch your data.
What you can do is use runGuardsAndResolvers in your route configuration like so:
const routes = [{
path: 'team/:id',
component: Team,
children: [{
path: 'user/:name',
component: User
}],
runGuardsAndResolvers: 'pathParamsChange',
resolvers: {...},
canActivate: [...]
}]
This will, as the name suggests, run your guard resolver logic again. If you fetch data using resolvers and pass it into your components, you can update what your component displays only when the path or params change.
I am using vue 2. I have registered routes. Two routes are memberships and memberships/:id.
When I use:
this.$router.push({ path: 'memberships'} );
after this any this.$router.push results in appending to
http://localhost:8000/memberships/bronze
http://localhost:8000/memberships/silver
and http://localhost:8000/memberships/shop in place of http://localhost:8000/shop
and http://localhost:8000/memberships/deals in place of http://localhost:8000/deals
Use a leading slash in all of your base route paths:
this.$router.push({ path: '/memberships' });
Do this in the base route definitions too. Also you can name your routes and push by name:
this.$router.push({ name: 'memberships'} );
I'm using nested routes so that might be causing the issue, however, I'm not sure how to fix it. I have the following route and children routes:
{
path: '/summoner/:summonerName',
component: Summoner,
children: [
{ path: '', component: Matchlist },
{ path: '/match/:matchId', component: SpecificMatch, name: 'specificMatch' }
]
},
When I'm on path /summoner/:summonerName I want to see the default Summoner parent component and the Matchlist component and when I'm on path /summoner/:summonerName/match/:matchId I want to see the default Summoner parent and the specificMatch child component. This works fine, however, when I try to use:
this.$router.push({ name: 'specificMatch', params: { summonerName: this.summoner, matchId: matchId, summonerInfo: this.summonerInfo, match: match}})
I get sent to /match/:matchId path instead of /summoner/:summonerName/match/:matchId which breaks the component because the components needs to get the username from the path. I assumed this.$router.push would send me to the correct path, alas no. Any tips how to fix this?
It's a matter of absolute and relative paths.
Your route with the name 'specificMatch' has the specified absolute path '/match/:matchId' so this is where you are navigated to. If you wish to append your path to the path of your parent route you will have to make your path relative, which means to leave out the initial slash (/) - e.i. path: 'match/:matchId'.
I have an Angular 2 test app running the latest alpha (37). There are just three routes, that look like this:
#RouteConfig([
{ path: '/', component: Home, as: 'home' },
{ path: '/errors', component: Errors, as: 'errors' },
{ path: '/about', component: About, as: 'about' }
])
I can access the routes, and when I place query string params in the URL I can read them just fine. However, a few instants after I read the parameters, I noticed that the route loads fine and the URL refreshes, removing the query string parameters.
In other words, accessing this route:
http://localhost:5555/errors?test=abc
Loads the /errors route, but right after the application loads the URL turns into:
http://localhost:5555/errors
That would be confusing to a user. I would like to keep the query string parameters in the URL.
I know, it's in alpha, but is this a bug or I forgot to set something up on the router? How can I keep whatever query string parameters in the URL?
Thanks!
This is fixed in Alpha 41. The query string is now persisted.
Updating for Angular 2:
To preserve query parameters present in the current url, add
// import NavigationExtras
import { NavigationExtras } from '#angular/router';
// Set our navigation extras object
// that contains our global query params
let navigationExtras: NavigationExtras = {
preserveQueryParams: true
};
// Navigate to the login page with extras
this.router.navigate(['/someLink'], navigationExtras);
For more info, check here:
Try this
this.router.navigate(['target'], {preserveQueryParams: true});