I'm Working with MEAN Stack , And i have 3 layouts and i want to protect every layout routes to prevent other layouts to access it
const routes: Routes = [
{
path: '',
redirectTo: '/dashboard',
pathMatch: 'full'
},
{
path: 'main-admin',
component: MainAdminLayoutComponent,
children: [
{
path: '',
loadChildren: () =>
import('./layouts/main-admin-layout/main-admin-layout.module').then(m => m.MainAdminLayoutModule)
}
]
},
{
path: 'main-admin',
component: MainAdminLayoutComponent,
loadChildren: () =>
import('./main-admin-components/main-admin.component.module').then(m => m.MainAdminComponentModule)
},
{
path: '',
component: AdminLayoutComponent,
children: [
{
path: '',
loadChildren: () =>
import('./layouts/admin-layout/admin-layout.module').then(m => m.AdminLayoutModule)
}
]
},
{
path: '',
component: AdminLayoutComponent,
loadChildren: () =>
import('./components/component.module').then(m => m.ComponentModule)
},
{
path: 'user',
component: SiteLayoutComponent,
children: [
{
path: '',
loadChildren: () =>
import('./layouts/site-layout/site-layout.module').then(m => m.SiteLayoutModule)
}
]
},
{
path: '',
component: UserLayoutComponent,
children: [
{
path: 'account',
loadChildren: () =>
import('./layouts/user-layout/user-layout.module').then(m => m.UserLayoutModule)
}
]
},
{
path: '**',
component: NotFoundComponent
}
];
Each route i want to protect ... Let's say i just a user and if i want to access admin routes redirect me to my dashboard
Any help please ??!!
The thing that you are trying to achieve over here is, users will have access to visit only particular components. In case if they are trying to visit a component for which they are not having access, they must be redirected to some other component.
This can be achieved by a feature called Angular Route Resolvers;. Usiing which you will run a piece of code before navigating ot that component and decide whether it can be navigated or not. You can find a detail implementation of route resolvers with example over here - https://dzone.com/articles/understanding-angular-route-resolvers-by-example
Related
CSS is not properly loading after redirect to home component in Angular.
I define my routes as
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'aboutus', component: AboutusComponent },
{ path: 'contactus', component: ContactusComponent },
{ path: 'boards', component: BoardsComponent },
{ path: 'board', component: BoardComponent },
{ path: '**', redirectTo: 'home', pathMatch: 'full' },
{ path: '*', redirectTo: 'home', pathMatch: 'full' },
{path: '', redirectTo:'/home', pathMatch: 'full' },
];
I tried different options but not succeeded, like
<a role="button" routerLink="../home" routerLinkActive="active">Home</a>
or
redirectToHome() {
this.router.navigate(['/home']);
}
home page like this before redirecting to another component
What's the issue?
On the left-side menu I need to have the links highlighted when the user on them. Now it works but my root path 'li' of the menu is highlighted as well.
I cannot set up a child routing Module.
left-side-menu html
<ul class='side-menu'>
<li *ngFor='let item of menu' routerLinkActive='active-side-menu-item'><a routerLink='{{ item.link }}' class="menu-item-feed">{{ item.title }}</a></li>
</ul>
app.routing.module ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { FeedComponent } from './feed/feed.component';
const routes: Routes = [
{ path: '', pathMatch: 'full', component: FeedComponent },
{ path: 'shoes', pathMatch: 'full', component: FeedComponent },
{ path: 'coats', pathMatch: 'full', component: FeedComponent },
{ path: 'shirts', pathMatch: 'full', component: FeedComponent },
{ path: 'pants', pathMatch: 'full', component: FeedComponent },
{ path: 'item/:id', component: FeedComponent },
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
That's how I tried to implement my childRoutingModule but it throws the error in the console: core.js:15724 ERROR Error: Uncaught (in promise): TypeError: undefined is not a function
TypeError: undefined is not a function
at Array.map ()
app.routing.module
const routes: Routes = [
{ path: '', pathMatch: 'full', loadChildren: './feed/feed.module#FeedModule' }
];
feed-routing.module
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { FeedComponent } from './feed.component';
const routes: Routes = [
{ path: '', pathMatch: 'full', component: FeedComponent },
{ path: 'shoes', pathMatch: 'full', component: FeedComponent },
{ path: 'coats', pathMatch: 'full', component: FeedComponent },
{ path: 'shirts', pathMatch: 'full', component: FeedComponent },
{ path: 'pants', pathMatch: 'full', component: FeedComponent },
{ path: 'item/:id', component: FeedComponent },
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class FeedRoutingModule { }
I want to have a separate routing module for each gross section on the site and I need link react to the url and indicate which module is active at the moment.
I would appreciate any other hints and best practices!
To setup feature route you have to import FeedRoutingModule into the module you want to use thoose route.
Below is my example
I have app.routing.ts (Main route)
export const routes: Routes = [
{ path: "", redirectTo: "home", pathMatch: "full" },
{ path: "home", component: HomeComponent },
//{ path: "**", redirectTo: "account", pathMatch: "full" },
//lazy load feature module
{ path: "account", loadChildren: "./account/account.module#AccountModule" },
{ path: "portal", loadChildren: "./portal/portal.module#PortalModule", canActivate: [AuthGuardService] },
{ path: "**", redirectTo: "account", pathMatch: "full" },
];
and app.module.ts
#NgModule({
declarations: [],
imports: [
RouterModule.forRoot(routes)
],
providers: [],
bootstrap: []
})
export class AppModule {}
So when I define child route in my feature module I have to done the same like app.module but using RouterModule.forChild
export const accountRoutes: Routes = [
{
path: "",
component: AccountComponent,
children: [
{ path: "login", component: LoginComponent },
{ path: "register-account", component: RegisterComponent }
]
}
];
import { NgModule } from "#angular/core";
import { CommonModule } from "#angular/common";
import { FormsModule, ReactiveFormsModule } from "#angular/forms";
import { RouterModule } from "#angular/router";
import { RegisterComponent } from "./register/register.component";
import { LoginComponent } from "./login/login.component";
import { AccountComponent } from "./account/account.component";
import { accountRoutes } from "./account.routing";
#NgModule({
declarations: [],
imports: [
RouterModule.forChild(accountRoutes) // use forChild
],
exports: [],
providers: []
})
export class AccountModule {}
Your paranet component need have tag: < router-outlet>< /router-outlet> then he knows will have a child component + route;
Here a exemple where i management childRoutes.
{
path: 'utente',
component: CenterViewComponent,
children: [
YYY_ROUTE,
XXX_ROUTE
...
]
}
Hope help u!
Basically the router.beforeEach() method is doing something I don't understand.
I get the jist of the issue being that when my route is re-directing to /login it will do it around 960 times or so until the error occurs.
my code is like so:
Router:
let router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path:'/login',
name: 'login',
component: Login,
meta: {
requiresAuth: 'false'
}
},
{
path:'/register',
name: 'register',
component: Register,
meta: {
requiresAuth: 'false'
}
},
{
path: '/',
name: 'home',
component: Home,
meta: {
requiresAuth: 'True'
}
}
]
})
the beforeEach() method
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
console.log(to.matched.some(record => record.meta.requiresAuth))
if (localStorage.getItem('jwt') == null) {
next({
path: '/login',
params: { nextUrl: to.fullPath }
})
} else {
next()
}
} else {
if (localStorage.getItem('jwt') != null) {
next({
path: '/',
params: { nextUrl: '/' }
})
} else {
next()
}
}
})
I've looked through countless threads and other places and none have the same issue as me (or I'm overlooking things). Anyone got an idea on how to fix, and what is actually happening to make the error occur in this? from what I can tell I have nothing named twice or any other function/component fire off when it shouldn't.
Fixed it. I'm a bit special in the head. For anyone with the same issue just change the routes to
routes: [
{
path: '/login',
name: 'login',
component: Login,
meta: {
requiresAuth: false
}
},
{
path:'/register',
name: 'register',
component: Register,
meta: {
requiresAuth: false
}
},
{
path: '/',
name: 'home',
component: Home,
meta: {
requiresAuth: true
}
}
]
For anyone who gets this error without any obvious mistake, try deleting node_modules and running npm install again.
I got this error when switching git branches and the only thing that changes were the packages, so I tried the above and it got rid of the problem :)
Have an angular 7 application and have implemented angular universal using node and express, and then deployed to firebase.
Having an issue when trying to load pages other than the root (/), which causes the server to return the html of the root (/) rather than the page the user requests.
Not sure from where the issue is originating (Angular, Angular Universal or Firebase).
This is my index.ts:
import * as functions from 'firebase-functions';
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import {renderModuleFactory} from '#angular/platform-server';
import {enableProdMode} from '#angular/core';
import * as express from 'express';
import {readFileSync} from 'fs';
enableProdMode();
const app = express();
const indexHtml = readFileSync(__dirname + '/index-server.html', 'utf-8').toString();
const {AppServerModuleNgFactory, LAZY_MODULE_MAP} = require('./main');
import {provideModuleMap} from '#nguniversal/module-map-ngfactory-loader';
app.engine('html', (_, options, callback) => {
// Always '/' (root path)
console.log('OPTIONS.REQ.URL', options.req.url);
renderModuleFactory(AppServerModuleNgFactory, {
// My index-server.html
document: indexHtml,
url: options.req.url,
extraProviders: [
provideModuleMap(LAZY_MODULE_MAP)
]
}).then(html => {
callback(null, html);
});
});
app.set('view engine', 'html');
app.set('views', __dirname);
app.get('*.*', express.static(__dirname + '/dist', {
maxAge: '1y'
}));
app.get('*', (req, res) => {
res.render(__dirname + '/index-server.html', {req});
});
exports.ssrApp = functions.https.onRequest(app);
This is my app-routing.module.ts:
import {RouterModule, Routes} from '#angular/router';
import {NgModule} from '#angular/core';
import {HomePageComponent} from './home-page/home-page.component';
import {ToursComponent} from './tours/tours.component';
import {MaltaComponent} from './malta/malta.component';
import {AboutComponent} from './about/about.component';
import {ContactComponent} from './contact/contact.component';
import {TourComponent} from './tours/tour/tour.component';
import {ErrorComponent} from './error/error.component';
import {BlogComponent} from './blog/blog.component';
import {BlogPageComponent} from './blog/blog-page/blog-page.component';
import {PageResolver} from './services/pages/page-resolver.service';
const AppRoutes: Routes = [
{
path: 'home',
component: HomePageComponent,
data: {
state: 'home',
pageId: 'home'
},
resolve: {
page: PageResolver
}
},
{
path: 'tours',
component: ToursComponent,
data: {
state: 'tours',
pageId: 'tours'
},
resolve: {
page: PageResolver
}
},
{
path: 'tours/:id',
component: TourComponent,
data: {
state: 'tour'
}
},
{
path: 'blog',
component: BlogComponent,
data: {
state: 'blogs',
pageId: 'blog'
},
resolve: {
page: PageResolver
}
},
{
path: 'blog/:id',
component: BlogPageComponent,
data: {
state: 'blog'
}
},
{
path: 'malta',
component: MaltaComponent,
data: {
state: 'malta',
pageId: 'malta'
},
resolve: {
page: PageResolver
}
},
{
path: 'about',
component: AboutComponent,
data: {
state: 'about',
pageId: 'about'
},
resolve: {
page: PageResolver
}
},
{
path: 'contact',
component: ContactComponent,
data: {
state: 'contact',
pageId: 'contact'
},
resolve: {
page: PageResolver
}
},
{
path: 'something-went-wrong',
component: ErrorComponent,
data: {
state: 'error',
pageId: 'error'
}
},
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
},
{
path: '**',
redirectTo: '/something-went-wrong'
}
];
#NgModule({
imports: [
RouterModule.forRoot(AppRoutes, {
useHash: true,
scrollPositionRestoration: 'enabled',
initialNavigation: 'enabled'
})
],
exports: [RouterModule]
})
export class AppRoutingModule {
}
This is my firebase.json:
{
"hosting": {
"public": "dist",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"function": "ssrApp"
}
]
},
"functions": {
"predeploy": "npm --prefix \"$RESOURCE_DIR\" run build"
}
}
Would appreciate any help with this issue!
The issue is solved after removing useHash: true from the app-routing.module.ts.
Thanks to yeya for helping get to the solution.
Your issue is related to Browser URL styles
Based on this answer: Try change the rewrites from "function": "ssrApp" to "destination": "/index-server.html"
The requestindex-server.html will trigger the function.
I am working on angular 6 .. I want to make the user redirects to specific route from outer link .. but when the user clicks the link he got redirected to "index"
and this is my routes
RouterModule.forRoot([
{ path: "Startup", component: StartupComponent },
{ path: "Login", component: SigninComponent },
{ path: "FirstPage", component: FirstPageComponent },
{ path: "Index", component: IndexComponent, canActivate: [ComponentGuardService] },
{ path: "Requests", component: IndexComponent, canActivate: [ComponentGuardService] },
{ path: "RequestsDetails/:id", component: RequestsDetailsComponent, canActivate: [ComponentGuardService] },
{ path: "RequestsStatistics", component: RequestsStatisticsComponent, canActivate: [AdminGuardService,ComponentGuardService] },
{ path: "", redirectTo: "Index", pathMatch: "full" },
{ path: "**", redirectTo: "Login", pathMatch: "full" }
], { useHash: true })
and ComponentGuardService
canActivate(): boolean {
let me = Shared.Me;
if (me == null || me.Id == "") {
this.navigator.navigate(["/Startup"]);
return false;
}
else
return true;
}
I want to make the user redirect to Requests route
thank you :)