I have a simple angular application and I am using Angular2 for the first time.
I am prompted with error in firefox console "EXCEPTION: Uncaught (in promise): Error: Cannot match any routes: 'books/huckleberry'"
book.component.ts
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
#Component({
selector: 'app-directory',
templateUrl: './book.component.html',
styleUrls: ['./book.component.css']
})
export class BookComponent implements OnInit {
book: string;
constructor(private route: ActivatedRoute) {
this.book= route.snapshot.params['book'];
}
ngOnInit() {
}
}
app.routes.ts
import { Routes, RouterModule } from "#angular/router";
import { BookComponent } from "./book/book.component";
import { HomeComponent } from "./home/home.component";
const APP_ROUTES: Routes = [
{
path:'book',
component: BookComponent,
children: [
{ path: 'book/:book', component: BookComponent}
]
},
{ path: '', component: HomeComponent }
];
export const APP_ROUTES_PROVIDER = RouterModule.forRoot(APP_ROUTES);
app.module.ts
...
import { BookComponent } from './book/book.component';
import { RouterModule } from "#angular/router";
#NgModule({
declarations: [
AppComponent,
BookComponent,
HomeComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot([
{ path: '', component: HomeComponent },
{ path: 'book', component: BookComponent },
// { path: '**', component: PageNotFoundComponent }
]),
RouterModule.forChild([
{
path: 'book', //parent path
children: [
{
path: 'book/:book',
component: BookComponent,
}
]
}
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
When i access http://localhost:4200/book, there is no error.
But when i access http://localhost:4200/book/huckleberry, using Angular2 for the first time.
I am prompted with error in firefox console "EXCEPTION: Uncaught (in promise): Error: Cannot match any routes: 'book/huckleberry'"
Do you know how can i update app.module.ts?
I should be able to get {{book}} in book.component.html
I was able to solve this by the following codes below:
app.routes.ts
const APP_ROUTES: Routes = [
{ path:'directory', component: BookComponent },
{ path:'directory/:book', component: BookComponent },
{ path: '', component: HomeComponent }
];
app.module.ts
#NgModule({
declarations: [
AppComponent,
DirectoryComponent,
HomeComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot([
{ path: '', component: HomeComponent },
{ path: 'book', component: BookComponent },
{ path: 'book/:book', component: BookComponent }
// { path: '**', component: PageNotFoundComponent }
])
],
providers: [],
bootstrap: [AppComponent]
})
With the code above, i am now able to get the parameter and print it to the page via {{book}}
Related
There are some similar discussions, but the solutions did not work. I've attempted to recreate the module a couple of times now and Angular still throws the error Maximum call stack size exceeded. The admin component is brand new as well. All of these have been generated using CLI.
Here's my code:
App Routing
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { AuthGuard } from './guards/auth/auth.guard';
const routes: Routes = [
{
path: 'dashboard',
pathMatch: 'full',
data: { authorized: [true] },
canActivate: [AuthGuard],
loadChildren: () =>
import('./modules/feature/dashboard/dashboard.module').then(
(m) => m.DashboardModule
),
},
///// this admin import is the issue and I know this because if I comment it out then the app works
///// fine...
{
path: 'admin',
pathMatch: 'full',
data: { authorized: [true] },
canActivate: [AuthGuard],
loadChildren: () =>
import('./modules/feature/admin/admin.module').then((m) => m.AdminModule),
},
{
path: '',
pathMatch: 'full',
data: { authorized: [false] },
loadChildren: () =>
import('./modules/feature/website/website.module').then(
(m) => m.WebsiteModule
),
},
// {
// path: '*',
// component: MainComponent,
// data: { authorized: [false] },
// },
];
#NgModule({
imports: [RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload' })],
exports: [RouterModule],
})
export class AppRoutingModule {}
Module
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { AdminRoutingModule } from 'src/app/routing/feature/admin-routing/admin-routing.module';
import { AdminComponent } from 'src/app/components/feature/admin/admin.component';
import { AdminService } from 'src/app/services/feature/admin.service';
#NgModule({
declarations: [AdminComponent],
imports: [CommonModule, AdminRoutingModule],
providers: [AdminService],
})
export class AdminModule {}
Admin Routing
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { AdminComponent } from 'src/app/components/feature/admin/admin.component';
const routes: Routes = [
{
path: '',
component: AdminComponent,
children: [],
},
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class AdminRoutingModule {}
Sometimes you bang your head against the wall because you've looked over your code a hundred times. Knowing good and well that it's not an error on your end. To find that the error can be solved via something simple. Like stopping the server, closing visual studio....re-opening visual studio and re-booting the server.
Which btw, solved my issue.
I am creating an Angular Application and I have used lazy Loading. When I am serving the application using ng serve --aot there is no error in the and also when I do ng build --prod still there is no error. But When I upload the build files in my hosting and trying to navigate from HOMEPAGE (https://pawsticks.rahuls.co.in) to LOGIN (https://pawsticks.rahuls.co.in/login) page there is an error in the terminal shows -
Uncaught (in promise): NullInjectorError: StaticInjectorError(i)[s -> e]:
StaticInjectorError(Platform: core)[s -> e]:
NullInjectorError: No provider for e!.
I am not getting it from where the error is occurring.
APP Module -
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule, routingComponents } from './app-routing.module';
import { HttpClientModule } from '#angular/common/http';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations'
import { DatePipe } from '#angular/common';
import { FeatureModule } from '#/modules/featured';
import { NgxSpinnerModule } from "ngx-spinner";
import { AppComponent } from '#/app.component';
#NgModule({
declarations: [
AppComponent,
routingComponents
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
BrowserAnimationsModule,
NgxSpinnerModule, // NGX Spinner
FeatureModule.forRoot() //Injecting Feature Module as ROOT Module
],
providers: [
DatePipe
],
bootstrap: [AppComponent]
})
export class AppModule { }
Feature Module:
import { NgModule, ModuleWithProviders } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule } from '#angular/router';
import { ReactiveFormsModule, FormsModule } from '#angular/forms';
//Importing HTTP Intercepter and services
import { HTTPInterceptorProvider } from '#/core/_HTTP-interceptor';
import { AjaxService, AuthTokenService, CommonHelperService } from '#/core/_services';
import { SummaryPipe } from '#/core/_pipes';
//Externel Plugins Modules
import { ShowHidePasswordModule } from 'ngx-show-hide-password';
import { NgxIntlTelInputModule } from 'ngx-intl-tel-input';
import { ImageCropperModule } from 'ngx-image-cropper';
import { BsDatepickerModule } from 'ngx-bootstrap/datepicker';
import { BsDropdownModule } from 'ngx-bootstrap/dropdown';
import { NgSelectModule } from '#ng-select/ng-select';
import { NgxPaginationModule } from 'ngx-pagination';
//Success Error Component, Password Strength Component, Animated Numbers Component
import {
SuccessErrorComponent,
PasswordStrengthBarComponent,
AnimatedNumbersComponent,
} from '#/modules/shared';
#NgModule({
declarations: [
SuccessErrorComponent,
PasswordStrengthBarComponent,
AnimatedNumbersComponent,
//Pipes used are listed here
SummaryPipe
],
imports: [
CommonModule,
ReactiveFormsModule,
FormsModule,
RouterModule,
NgxIntlTelInputModule,
ShowHidePasswordModule, // Show Hide Password Plugin Import
ImageCropperModule, // Image cropper Module
BsDatepickerModule.forRoot(), //Bootstrap Datepicker Plugin
BsDropdownModule.forRoot(),
NgSelectModule,
NgxPaginationModule
],
providers: [
],
exports: [
SuccessErrorComponent,
PasswordStrengthBarComponent,
AnimatedNumbersComponent,
SummaryPipe,
ReactiveFormsModule,
FormsModule,
NgxIntlTelInputModule,
ImageCropperModule, // Image cropper Module
BsDatepickerModule, //Bootstrap Datepicker Plugin
BsDropdownModule,
NgSelectModule,
NgxPaginationModule,
ShowHidePasswordModule
]
})
export class FeatureModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: FeatureModule,
providers: [
HTTPInterceptorProvider,
AjaxService,
AuthTokenService,
CommonHelperService
]
};
}
}
App Routing Module :
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { CustomPreloadingStrategy } from './preloading-strategy';
import { AuthGuard, SecureOuterPagesGuard } from "#/core/_guards";
// Home page of the application
import { IndexComponent } from '#/modules/index/index.component';
// Authentication and Authorization Components
import {
LoginComponent,
RegisterComponent,
VerifyAccountComponent,
VerifyAccountStatusComponent,
ForgetPasswordComponent,
ResetPasswordComponent
} from '#/modules/auth';
// Session Timeout, Page Not Found and Interner Server Error Components
import {
SessionTimeOutComponent,
PageNotFoundComponent,
InternalServerErrorComponent
} from '#/modules/shared';
const routes: Routes = [
{
path: '',
component: IndexComponent
},
{
path: 'login',
component: LoginComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'register',
component: RegisterComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'verify-account',
component: VerifyAccountComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'verify-account-status',
component: VerifyAccountStatusComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'forget-password',
component: ForgetPasswordComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'reset-password',
component: ResetPasswordComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'dashboard',
loadChildren: () => import('./modules/dashboard/dashboard.module').then(m => m.DashboardModule),
canActivate: [AuthGuard],
data: { preload: true }
},
{
path: 'internal-server-error',
component: InternalServerErrorComponent
},
{
path: 'page-not-found',
component: PageNotFoundComponent
},
{
path: 'session-time-out',
component: SessionTimeOutComponent
},
{
path: '**',
component: PageNotFoundComponent
}
];
#NgModule({
imports: [RouterModule.forRoot(routes, { preloadingStrategy: CustomPreloadingStrategy })],
exports: [RouterModule],
providers: [CustomPreloadingStrategy]
})
export class AppRoutingModule { }
export const routingComponents = [
IndexComponent,
LoginComponent,
RegisterComponent,
VerifyAccountComponent,
VerifyAccountStatusComponent,
ForgetPasswordComponent,
ResetPasswordComponent,
SessionTimeOutComponent,
PageNotFoundComponent,
InternalServerErrorComponent,
]
I'm creating an application with Angular 9 where I've created a separate routing module for the admin purpose and calling it in app.module to initialize. But for some reason the routes are not getting called and and the below error is coming in the console.
ERROR Error
Angular 11
resolvePromise
resolvePromise
scheduleResolveOrReject
invokeTask
onInvokeTask
invokeTask
runTask
drainMicroTaskQueue
invokeTask
invoke
timer
core.js:3872
I've created child modules like this in previous versions of Angular and it worked perfectly. You can check my github repository if you want to https://github.com/tridibc2/sample-angular. Have a look at my modules below
AdminModule:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { Routes, RouterModule } from '#angular/router';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { AdminComponent } from '../admin/admin.component';
import { SignupComponent } from '../signup/signup.component';
import { LoginComponent } from '../login/login.component';
import { ManageBlogsComponent } from '../manage-blogs/manage-blogs.component';
const routes: Routes = [
{ path: 'signup', component: SignupComponent },
{ path: 'login', component: LoginComponent },
{ path: 'admin', component: AdminComponent },
{ path: 'admin/blog', component: ManageBlogsComponent }
];
#NgModule({
declarations: [
AdminComponent,
SignupComponent,
LoginComponent,
ManageBlogsComponent
],
imports: [
RouterModule.forChild(routes),
CommonModule,
FormsModule,
ReactiveFormsModule
],
exports: [RouterModule]
})
export class AdminModule { }
app.module.ts:
import { BrowserModule } from '#angular/platform-browser';
import { HttpClientModule } from '#angular/common/http';
import { CommonModule } from '#angular/common';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { RouterModule } from '#angular/router';
import { ClientModule } from './client/client-routing/client.module';
import { AdminModule } from './admin/admin-routing/admin.module';
import { AppRoutingModule } from './app.routing';
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent ],
imports: [
BrowserModule,
CommonModule,
NgbModule,
ClientModule,
AdminModule,
AppRoutingModule,
FormsModule,
RouterModule ],
bootstrap: [AppComponent]
})
export class AppModule { }
app.routing.ts:
import { NgModule } from '#angular/core';
import { CommonModule, } from '#angular/common';
import { BrowserModule } from '#angular/platform-browser';
import { Routes, RouterModule } from '#angular/router';
import { BlogHomeComponent } from './client/blog-home/blog-home.component';
const routes: Routes =[
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: BlogHomeComponent }
];
#NgModule({
imports: [
CommonModule,
BrowserModule,
RouterModule.forRoot(routes,{
useHash: true
})
],
exports: [
],
})
export class AppRoutingModule { }
Simple example for routing of eager loaded module.
Ref of atleast one component is required in parent module and which is mostly a component that has router-outlet tag to render child module routes.
...
const routes: Routes = [
{
path: '',
component: CompWhichHasRouterOutletTag,
children:[
{path: '', redirectTo: 'signup', pathMatch: 'full'},
{ path: 'signup', component: SignupComponent },
{ path: 'login', component: LoginComponent },
{ path: 'admin', component: AdminComponent },
{ path: 'admin/blog', component: ManageBlogsComponent }]
}
];
#NgModule({
declarations: [
CompWhichHasRouterOutletTag,
AdminComponent,
SignupComponent,
LoginComponent,
ManageBlogsComponent
],
imports: [
RouterModule.forChild(routes),
CommonModule,
FormsModule,
ReactiveFormsModule
],
exports: [RouterModule, CompWhichHasRouterOutletTag]
})
export class AdminModule { }
app.routing.ts file
const routes: Routes = [
{ path: '', redirectTo: '/home/', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'contact', component: ContactComponent },
{ path: 'admin-route', component: CompWhichHasRouterOutletTag },
]
#NgModule({
imports: [
...
RouterModule.forRoot(routes),
...
]
})
So basically I am trying to create a lazy loaded feature module in my application I have been following the official angular docs - but for some reason its not working.
I have set up my feature module DashboardModule as shown below
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
// MODULES
import { DashboardRoutingModule } from './dashboard-routing.module';
// COMPONENTS
import { DashboardComponent } from './dashboard/dashboard.component';
import { DashboardAlertComponent } from './dashboard-alert/dashboard-alert.component';
import { DashboardSummaryComponent } from './dashboard-summary/dashboard-summary.component';
import { DashboardTasksComponent } from './dashboard-tasks/dashboard-tasks.component';
import { HoldingPageComponent } from './holding-page/holding-page.component';
#NgModule({
imports: [CommonModule, DashboardRoutingModule],
declarations: [
DashboardComponent,
DashboardAlertComponent,
DashboardSummaryComponent,
DashboardTasksComponent,
HoldingPageComponent,
]
})
export class DashboardModule {}
then in my DashboardRoutingModule
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { ActivityComponent } from '../activity-components/activity/activity.component';
import { IsLockedRouteGuard } from '#app/shared/common/auth/is-locked-route-guard';
import { DashboardSummaryComponent } from './dashboard-summary/dashboard-summary.component';
import { SyncComponent } from '#app/popup-components/sync/sync.component';
import { DashboardAlertComponent } from './dashboard-alert/dashboard-alert.component';
import { ChartContainerComponent } from '../chart-components/chart-container/chart-container.component';
import { DashboardTasksComponent } from './dashboard-tasks/dashboard-tasks.component';
#NgModule({
imports: [
RouterModule.forChild([
{ path: 'activity', component: ActivityComponent, canActivate: [IsLockedRouteGuard] },
{ path: 'snapshot', component: DashboardSummaryComponent },
{ path: 'sync', component: SyncComponent },
{
path: 'alerts',
component: DashboardAlertComponent,
canActivate: [IsLockedRouteGuard]
},
{ path: 'charts', component: ChartContainerComponent, canActivate: [IsLockedRouteGuard] },
{ path: 'tasks/:sort', component: DashboardTasksComponent, canActivate: [IsLockedRouteGuard] },
])
],
exports: [RouterModule]
})
export class DashboardRoutingModule {}
so as per the angular docs this has been set up correctly..
now in my AppRoutingModule
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { AppComponent } from './app.component';
import { AppRouteGuard } from './shared/common/auth/auth-route-guard';
#NgModule({
imports: [
RouterModule.forChild([
{
path: 'app',
component: AppComponent,
children: [
{
path: '',
children: [{ path: '', redirectTo: '/dashboard/alerts', pathMatch: 'full' }]
},
{
path: 'main',
canActivate: [AppRouteGuard],
loadChildren: () => import('./main/main.module').then(m => m.MainModule),
data: { preload: true }
},
{
path: 'dashboard',
loadChildren: () => import('./main/dashboard/dashboard.module').then(m => m.DashboardModule)
},
]
}
])
],
exports: [RouterModule]
})
export class AppRoutingModule {}
but whats happening is when I try and go to /dashboard.. I get this error
Component HoldingPageComponent is not part of any NgModule or the module has not been imported into your module.
but I am clearly importing it in the DashboardModule as shown above.. what am I doing wrong??
Thanks
i don't see
RouterModule.forRoot
i think you should use it in AppRoutingModule instead of
RouterModule.forChild
how can I make sure to have at least 2 router-outlets and manage them at the routing level?
can link me a working jsfillde or stackblitz or similar?
edited re open problem
APP COMPONENT HTML
<main [#fadeInAnimation]="o.isActivated ? o.activatedRoute : ''">
<router-outlet #o="outlet" name="main"></router-outlet>
<router-outlet #o="outlet" name="second"></router-outlet>
</main>
APP MODULE
import { BrowserModule } from '#angular/platform-browser';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { HttpClientModule } from '#angular/common/http';
import { NgModule, APP_INITIALIZER } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
// components
import { AppComponent } from './app.component';
import { HomeComponent } from './components/home/home.component';
// models
import { Permissions } from '../app/models/permissions';
// guards
import { CanAccess } from '../app/guards/canaccess';
import { OtherComponent } from './components/other/other.component';
import { PageNotFoundComponent } from './components/page-not-found/page-not-found.component';
const permissions: Permissions = new Permissions();
const appRoute: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent, data: { permission: permissions }, canActivate: [CanAccess], outlet: 'main' },
{ path: 'other', component: OtherComponent, data: { permission: permissions }, canActivate: [CanAccess], outlet: 'second' },
{ path: 'pageNotFound', component: PageNotFoundComponent, data: { permission: permissions }, canActivate: [CanAccess], outlet: 'main' },
{ path: '**', redirectTo: 'pageNotFound', pathMatch: 'full' },
];
export function appConfigFactory() {
try {
return () => true;
} catch (e) {
console.log(`catch load: ${e}`);
}
}
#NgModule({
declarations: [
AppComponent,
HomeComponent,
OtherComponent,
PageNotFoundComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
HttpClientModule,
RouterModule.forRoot(appRoute)
],
providers: [
CanAccess,
{
provide: APP_INITIALIZER,
useFactory: appConfigFactory,
deps: [],
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
ERROR
ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'home'
Error: Cannot match any routes. URL Segment: 'home'
can view on editor
https://stackblitz.com/edit/angular-ghusfs
thanks
You may define parent child component to use multiple router-outlets like this.
{
path: 'shop', component: ParentShopComponent,
children : [{
path: 'hello', component: ChildShopComponent
}]
}
Your first <router-outlet> will be in app component & second in ParentShopComponent rest of components can lend in child level or parent.
But if your relationship is child parent than check this out Named Router Outlets
Example
This is main Router OUtlet
These are named ones
<div class="columns">
<md-card>
<router-outlet name="list"></router-outlet>
</md-card>
<md-card>
<router-outlet name="bio"></router-outlet>
</md-card>
</div>
And here's how you use them
{ path: 'speakersList', component: SpeakersListComponent, outlet: 'list' }