Angular2 CanActivate guard for all routes except one - javascript

I know that we can group routes located in one module. Like that:
canActivate: [AuthGuard],
children: [
{
path: '',
children: [
{ path: 'crises', component: ManageCrisesComponent },
{ path: 'heroes', component: ManageHeroesComponent },
{ path: '', component: AdminDashboardComponent }
],
}
But I should add that guard to each module's routing file. And I have many of them.
I want that the user can not go to any route except one (login route) if he is not authorized.
What is the right way to add guard to all of them??

You can use a componentless empty path parent route with the guard
{ path: '', canActivate: [AuthGuard], children: [
{
path: '',
children: [
{ path: 'crises', component: ManageCrisesComponent },
{ path: 'heroes', component: ManageHeroesComponent },
{ path: '', component: AdminDashboardComponent }
],
}
}
and in the guard check if the user is logged in.
If not logged in and the current route is login then still allow it.

Related

angular JavaScript not working in children component, left side nav dropdown is not working

i have a left side navigation in home component, the navigation dropdown is not working in one of the routing module (admin-routing.module.ts).
the navigation is working in app-routing.module.ts "path:'home'"
the component file is same in the two routing modules
i am new in angular, i am using angular 14v
i have a component name with "home"
i used two routing
app-routing.module.ts
admin-routing.module.ts
This goes inside app-routing.module.ts
const routes: Routes =
[
{ path: 'login', component: LoginComponent },
{ path: 'forgot-password', component: ForgotPasswordComponent },
{ path: 'not-found', component: NotFoundComponent },
{ path: '', redirectTo: 'login', pathMatch: 'full' },
{
path: 'admin',
loadChildren: () =>
import('./modules/admin/admin.module').then((m) => m.AdminModule)
},
{path:'home', component:HomeComponent},
{ path: '**', component: NotFoundComponent },
];
This goes inside admin-routing.module.ts
const routes: Routes = [
{
path: '',
component: HomeComponent,
children: [
{ path: '', redirectTo: 'dashboard', pathMatch: 'full'},
{ path: 'dashboard', component: DashboardComponent }
]
}
];
i also added the script file path in angular.json
the navigation dropdown and toogle is not working in admin-routing.module.ts's "home path"
i hosted these files in my server
working navigation link is http://angular.byteinnovations.in/home
this navigation is not working http://angular.byteinnovations.in/admin/home
As i see in your routing
const routes: Routes = [
{
path: '',
component:HomeComponent,
children:
[
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent }
]
}
];
You are using HomeComponent two times can you check and do it in this way on your adminRouting Module
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent }
]

Rerouting sub paths to a main path in angular

In my routes file I am trying to achieve the following.
const routes: Routes = [{ ...
{ path: '', component: MainComponent, children: [
{ path: 'routeA', component: ComponentA },
{ path: 'routeA/subA', component: ComponentAA},
{ path: 'routeA/subB', component: ComponentAB},
{ path: 'routeA/**', redirectTo: 'routeA'}
]}, ...}
The intention being that routeA/ will redirect back to routeA, but the above code doesnt achieve the intended effect.

Problem with programmatic navigation in vue.js

I'm developing a Vue.js application and there is something that I can't figure out about programmatic navigation.
As you can see below in my index.js file I have a tree structured routes in my client, some of this route need to be protected.
The routes that must be protected are the ones that are child of 'dashboard'.
When the App is loaded, if the user try to navigate one of those protected routes, the client send a request to the server, asking if the token that he possess allow him to access those protected routes, if the answer is yes then the user can freely navigate, otherwise I want to redirect him to the login page.
The problem arise here, how you can see from the 'App.vue' if the request checkSession fail (meaning no valid token has been provided) the error will be catched and this.$router.push('/login') is executed, but without success, in fact the url does not change at all.
I tried to print the router object and I have noticed that the route that I'm trying to push appear under history.pending properties of the cited object.
Another weird thing that I've noticed: if I delete the redirect in the routes path (the very last one) declared in the 'index.js' file and I load the App through an url that does not belong to one of the declared routes, for example '/wrong/path', and the user does not provide a valid token then $router.push('/login') works fine.
index.js
...
const routes = [{
path: '/login',
name: 'login',
component: LoginComponent
},
{
path: '/',
name: 'dashboard',
redirect : '/dipendenti/aggiungi',
component: DashboardComponent,
children: [
{ path: 'dipendenti', component: MiddleWareComponent, children:[
{ path: 'aggiungi', component: AddWorkerComponent },
{ path: 'elimina', component: DeleteWorkerComponent },
{ path: 'modifica', component: ModifyWorkerComponent }
]},
{ path: 'clienti', component: MiddleWareComponent, children:[
{ path: 'aggiungi', component: AddClientComponent },
{ path: 'modifica', component: ModifyClientComponent }
]},
{ path: 'team', component: MiddleWareComponent, children:[
{ path: 'aggiungi', component: AddTeamComponent },
{ path: 'elimina', component: DeleteTeamComponent },
{ path: 'modifica', component: ModifyTeamComponent }
]},
{ path: 'lavori', component: MiddleWareComponent, children:[
{ path: 'visualizza', component: ViewWorkComponent },
{ path: 'aggiungi', component: AddWorkComponent },
{ path: 'elimina', component: DeleteWorkComponent },
{ path: 'modifica', component: ModifyWorkComponent }
]},
{ path: 'account', component: MiddleWareComponent, children:[
{ path: 'modifica', component: ModifyAccountComponent }
]}
]
},
{ path: '/logout', component: LogoutComponent },
{ path: '/password-forgot', component: PasswordForgotComponent },
{ path: '/password-reset/:token/:api', component: PasswordResetComponent },
{ path: '/*', redirect : '/' }
];
const router = new VueRouter({
routes: routes,
base: __dirname,
base: process.env.BASE_URL,
mode: 'history'
});
...
App.vue
<script>
import Vue from 'vue';
import axios from 'axios';
Vue.prototype.$https = axios.create({
baseURL: 'http://localhost:5000',
withCredentials: true,
crossdomain: true
});
Vue.prototype.$checkSession = function() {
if (window.location.pathname != '/login' && window.location.pathname != '/password-forgot' && window.location.pathname.split('/')[1] != 'password-reset') {
var authToken = localStorage.authToken? localStorage.authToken:sessionStorage.authToken;
this.$https.defaults.headers.common['x-csrf-token'] = authToken;
this.$https.get('api/web/user/session').then(response => {
if(window.location.pathname == '/'){
this.$router.push('/dipendenti/aggiungi');
}
}).catch(e => {
console.log(this.$router.app);
this.$router.push('/login');
})
}
}
...
export default {
name: 'app',
created: function() {
this.$checkSession();
}
};
</script>
The desired behavior would be the redirect to the login page.

back button going back to login page instead of home page in angular 4

I am facing weird problem with back button press on browser, I have login page when i click on login page it goes to home page..
In the home page i have menu options like reports and sales when i click on reports page it goes to reports page.
My problem is when i click on browser back button on reports page it goes to login page instead of home page
URL for Home page : /localhost:4200/home
URL for reports Page : /localhost:4200/home/monthlyreport/my
and i have written code for browser back button below
import { PlatformLocation, Location } from '#angular/common'
constructor(private location: PlatformLocation, private loc: Location) {
location.onPopState(() => {
//window.history.back();
this.loc.back(); // tried with this one but no result
});
}
Could any one please help on this how to back to previous page using angular 4
Many thanks in advance..
updated login action method
const routes: Routes = [
{
path: "",
redirectTo: "login",
pathMatch: "full"
},
{
path: "login",
component: LoginComponent
},
{
path: "error/:errorId",
component: ErrorComponent
},
{
path: "logout",
component: LogoutComponent
},
{
path: "home",
data: {
breadcrumb: "Home"
},
component: HomeComponent,
}
children: [
{
path: "monthlyreport/:type",
data: {
breadcrumb: "Reports"
},
component: MonthlyReportComponent,
canActivate: [AuthGuardService]
}
]
];
I believe you should rewrite your code as the following:
{
path: "home",
data: {
breadcrumb: "Home"
},
component: HomeComponent,
children: [
{
path: "monthlyreport/:type",
data: {
breadcrumb: "Reports"
},
component: MonthlyReportComponent,
canActivate: [AuthGuardService]
}
]
}
];
Which will bring the structure of the object in line with the example used in the Angular documentation here
const crisisCenterRoutes: Routes = [
{
path: 'crisis-center',
component: CrisisCenterComponent,
children: [
{
path: '',
component: CrisisListComponent,
children: [
{
path: ':id',
component: CrisisDetailComponent
},
{
path: '',
component: CrisisCenterHomeComponent
}
]
}
]
}
];

Angular Routes not mapping properly for lazy loading

So I have an app with multiple modules that has routes properly put in place, and each module has it's own routes. Everything works fine, until I try to implement lazy loading.
Previous State:
example module
export const EXAMPLE_ROUTES: Routes = [
{ path: 'new', component: AddOpportunityComponent },
{ path: ':id', component: OpportunityProfileComponent,
children: [
{
path: 'edit/sdg-info', component: SdgInfoComponent
}
]}
];
I import this EXAMPLE_ROUTES in example module
Now I have root level routing as
const APP_ROUTES: Routes = [
{ path: '', component: HomeComponent},
{ path: 'search', component: SearchComponent },
{ path: 'example', component: ExampleComponent, children: [...EXAMPLE_ROUTES], canActivate: [AuthGuard, OnboardedGuard] },
];
export const appRouting = RouterModule.forRoot(APP_ROUTES, {enableTracing: true});
With this setup it works fine
After trying to have lazy loading
example module
const EXAMPLE_ROUTES: Routes = [
{ path: 'new', component: AddOpportunityComponent },
{ path: ':id', component: OpportunityProfileComponent,
children: [
{
path: 'edit/sdg-info', component: SdgInfoComponent
}
]}
];
export const exampleRouting = RouterModule.forChild(EXAMPLE_ROUTES);
and app routing becomes
const APP_ROUTES: Routes = [
{ path: '', component: HomeComponent},
{ path: 'search', component: SearchComponent },
{ path: 'example', loadChildren: './example/example.module#ExampleModule', canActivate: [AuthGuard, OnboardedGuard] }
];
export const appRouting = RouterModule.forRoot(APP_ROUTES, {enableTracing: true});
The problem I'm facing is, the example route works fine, now the /search route breaks, as the router for some reason tries to match it with opportunity route (path: ':id')
What might be going wrong here?
This issue can occoure when you first implement your FeatureModule in your RootModule and after a given time you decide you want to load this FeatureModule lazy via loadChildren and you forgot to remove FeatureModule from your imports in your RootModule.
In your case your Routing Configuration will look something like this after compilation (PSEUDO-CODE):
const Routes_CONFIG = [
{ path: '', component: HomeComponent},
{ path: 'search', component: SearchComponent },
{ path: 'example', loadChildren: './example/example.module#ExampleModule', canActivate: [AuthGuard, OnboardedGuard] }
{ path: 'new', component: AddOpportunityComponent },
{ path: ':id', component: OpportunityProfileComponent,
children: [
{ path: 'edit/sdg-info', component: SdgInfoComponent }
]
}
]
In your case, when you just enter /search you will match :id OpportunityProfileComponent. That's because the router accepts the first route that matches a navigation request path.

Categories

Resources