When running ng serve with a successful compilation in my Angular app, I started getting the following error in the browser console.
AppComponent_Host.ngfactory.js? [sm]:1 ERROR Error: Arguments array must have arguments.
at injectArgs (core.js:1412)
at core.js:1491
at _callFactory (core.js:8438)
at _createProviderInstance (core.js:8396)
at resolveNgModuleDep (core.js:8371)
at NgModuleRef_.push../node_modules/#angular/core/fesm5/core.js.NgModuleRef_.get
(core.js:9064)
at resolveDep (core.js:9429)
at createClass (core.js:9309)
at createDirectiveInstance (core.js:9186)
at createViewNodes (core.js:10406)
This as far as I can tell from Main.ts platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));
I have deleted the node modules folder and reinstalled and I'm having trouble with the lack of explanation the error gives. Plus, I'm somewhat new to Angular.
Any help would be greatly appreciated.
EDIT
I ran ng serve --aot and got the following error
ERROR in : Error: Internal error: unknown identifier []
at Object.importExpr$$1 [as importExpr] (C:\Users\kg\Documents\ang2\ad\UI\node_modules\#angular\compiler\bundles\compiler.umd.js:21731:27)
at C:\Users\kg\Documents\ang2\ad\UI\node_modules\#angular\compiler\bundles\compiler.umd.js:9988:37
at Array.map (<anonymous>)
at InjectableCompiler.depsArray (C:\Users\kg\Documents\ang2\ad\UI\node_modules\#angular\compiler\bundles\compiler.umd.js:9954:25)
at InjectableCompiler.factoryFor (C:\Users\kg\Documents\ang2\ad\UI\node_modules\#angular\compiler\bundles\compiler.umd.js:10018:36)
at InjectableCompiler.injectableDef (C:\Users\kg\Documents\ang2\ad\UI\node_modules\#angular\compiler\bundles\compiler.umd.js:10037:42)
at InjectableCompiler.compile (C:\Users\kg\Documents\ang2\ad\UI\node_modules\#angular\compiler\bundles\compiler.umd.js:10047:106)
at C:\Users\kg\Documents\ang2\ad\UI\node_modules\#angular\compiler\bundles\compiler.umd.js:21576:90
at Array.forEach (<anonymous>)
at AotCompiler._emitPartialModule2 (C:\Users\kg\Documents\ang2\ad\UI\node_modules\#angular\compiler\bundles\compiler.umd.js:21576:25)
at C:\Users\kg\Documents\ang2\ad\UI\node_modules\#angular\compiler\bundles\compiler.umd.js:21569:48
at Array.reduce (<anonymous>)
at AotCompiler.emitAllPartialModules2 (C:\Users\kg\Documents\ang2\ad\UI\node_modules\#angular\compiler\bundles\compiler.umd.js:21568:26)
at AngularCompilerProgram._emitRender2 (C:\Users\kg\Documents\ang2\ad\UI\node_modules\#angular\compiler-cli\src\transformers\program.js:364:31)
at AngularCompilerProgram.emit (C:\Users\kg\Documents\ang2\ad\UI\node_modules\#angular\compiler-cli\src\transformers\program.js:236:22)
at AngularCompilerPlugin._emit (C:\Users\kg\Documents\ang2\ad\UI\node_modules\#ngtools\webpack\src\angular_compiler_plugin.js:846:49)
ngModule
#NgModule({
declarations: [
AppComponent,
LoginComponent,
ItemDashboardComponent,
UnprotectedSearchComponent,
HomeComponent,
UnprotectedResultsComponent,
DashboardComponent,
TrackingListComponent,
ListItemComponent,
ActionItemComponent,
ActionListComponent,
ItemInfoTableComponent,
TrackingInfoTableComponent,
FilterPipe,
RegisterItemsComponent,
RegisterPackageComponent,
AddItemsPackageComponent,
ChangeCustodyComponent,
CheckTempComponent,
RemoveItemsComponent,
ScannerComponent,
ContainerDashboardComponent,
SoldComponent
],
imports: [
NgQrScannerModule,
MatTabsModule,
AngularFontAwesomeModule,
MatListModule,
MatFormFieldModule,
BrowserAnimationsModule,
MatMenuModule,
MatProgressBarModule,
BrowserModule,
MatIconModule,
MatGridListModule,
AngularFontAwesomeModule,
FormsModule,
AppRoutingModule,
HttpClientModule,
RouterModule.forRoot([
{
path: 'home',
component: HomeComponent
},
//{path: 'openSearch', component: LoginComponent},
{
path: 'item',
component: ItemDashboardComponent,
canActivate: [AuthGuard, ManufacturerAuthGuardService]
},
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [AuthGuard]
},
{
path: 'unprotectedResults',
component: UnprotectedResultsComponent,
canActivate: [AuthGuard]
},
{
path: 'trackingList/'+environment.config.itemWorkflow+'/:contractId',
component: ItemDashboardComponent,
canActivate: [AuthGuard]
},
{
path: 'trackingList/'+environment.config.packageWorkflow+'/:contractId',
component: ContainerDashboardComponent,
canActivate: [AuthGuard]
},
{
path: 'trackingList',
component: TrackingListComponent,
canActivate: [AuthGuard]
},
{
path: 'actions',
component: ActionListComponent,
canActivate: [AuthGuard]
},
{
path: 'publicResults/:contractId',
component: UnprotectedResultsComponent
},
{
path: 'registerItems',
component: RegisterItemsComponent,
canActivate: [AuthGuard]
},
{
path: 'addItemsToPackage',
component: AddItemsPackageComponent,
canActivate: [AuthGuard]
},
{
path: 'registerPackage',
component: RegisterPackageComponent,
canActivate: [AuthGuard]
},
{
path: 'changeCustody/:contractId',
component: ChangeCustodyComponent,
canActivate: [AuthGuard]
},
{
path: 'changeCustody',
component: ChangeCustodyComponent,
canActivate: [AuthGuard]
},
{
path: 'checkTemp',
component: CheckTempComponent,
canActivate: [AuthGuard]
},
{
path: 'removeItems',
component: RemoveItemsComponent,
canActivate: [AuthGuard]
},
{
path: 'sellItems',
component: SoldComponent,
canActivate: [AuthGuard]
},
]),
UiModule
],
providers: [
AuthGuard,
{
provide: HTTP_INTERCEPTORS,
useClass: MyInterceptor,
multi: true
},
MockBackend,
fakeBackendProvider,
BaseRequestOptions,
AuthGuard,
AdminAuthGuard,
AdalService,
SoldComponent
],
bootstrap: [AppComponent]
})
AppComponent Constructor
constructor(private api: ApiService, private adalService: AdalService, private _http: HttpClient, private router: Router, public authService: AuthService) {
this.adalService.init(environment.config);
if (!this.adalService.userInfo.authenticated) this.router.navigate(['/']);
}
First, try building/serving the app with ng serve --aot flag. Chances are some warning/error will be shown at the compile time.
As far as I can think, can you search in your project, if you are importing any component/module
like this import {something} from "../node_modules/#somepackage/adfas"; instead of import {something} from "#somepackage/adfas";
Also can you please share what you have in #NgModule({}) decorator, and in AppComponent constructor();
I think the angular is not able to provide all the injected dependencies.
I had the same error because of a circular dependency in my code:
Service1 > Service2 > Service1
i had the same issue, just tried to start app again and it worked.
In my case I was missing the injected type in the constructor :/
This Typescript snippet demonstrates a scenario which causes this error.
...
export class AClassImportingAService {
constructor(private _importedService) {
// ERROR: notice there is no type on _importedService
// It should read 'private _importedService: ImportedService'
}
...
}
I had same error, when #Injectable decorator and export keyword were not used for a dependency.
I received this error due to having a circular dependency. I had a store which depended on some initial state which was provided by a service that depended on my store.
I resolved the issue by extracting the initial state, which was a constant object, to its own constants file.
I made a typo instead of ":" I used "," in the constructor and had this error:
constructor(private myService, Myservice) {
}
//instead of
constructor(private myService: Myservice) {
}
Related
I configured my app in two levels for nested routing as shown in the snapshot image.
the content of app modules is:
app.module.ts
#NgModule({
declarations: [
AppComponent,
DashboardComponent,
TeacherMembershipComponent,
StudentMembershipComponent,
RulesComponent,
ContactInfoComponent,
Page404Component,
UserProfileComponent,
NotificationsComponent,
GeneralComponent,
ReportComponent
],
// ...
and app-routing.module.ts
const routes: Routes = [
{
path: 'dashboard',
component: DashboardComponent
},
{
path: 'userProfile',
component: UserProfileComponent
},
{
path: 'general',
component: GeneralComponent
},
{
path: 'report',
component: ReportComponent
},
{
path: 'notifications',
component: NotificationsComponent
},
{
path: "department/:dep", loadChildren: () => import(`./branches/branches.module`).then(m => m.BranchesModule)},
{
path: 'aboutUs/rules',
component: RulesComponent
},
{
path: 'aboutUs/contactInfo',
component: ContactInfoComponent
},
{
path: 'membership/teacher',
component: TeacherMembershipComponent
},
{
path: 'membership/student',
component: StudentMembershipComponent
},
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
{ path: '**', component: Page404Component },
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
the second level is branches that its modules are:
branches.module.ts:
#NgModule({
declarations: [
BranchesComponent,
CoursesListComponent,
TeachersListComponent,
TeacherResumeComponent,
TeacherSelectionFormComponent,
Page404BranchesComponent
],
imports: [
CommonModule,
BranchesRoutingModule,
MaterialDesignModule
]
})
export class BranchesModule { }
and branches-routing.module.ts:
const routes: Routes = [
{ path: '', component: BranchesComponent, children: [
{
path: "coursesList/:branchCourses",
component: CoursesListComponent
},
{
path: "teacherSelection",
component: TeacherSelectionFormComponent
},
{
path: "teacherResume",
component: TeacherResumeComponent
},
{
path: 'coursesList', component: CoursesListComponent
},
{
path: '', redirectTo: 'coursesList', pathMatch: 'full'
},
{
path: '**', component: Page404BranchesComponent
},
]}
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
till here, when one of links (departments) in sidenav of app.component.html is clicked, the branches.component is loaded in place of route-outlet of app.component and subscribes the parameters passed from app.component, and lists branches respected to each link.
baranch.component.ts:
export class BranchesComponent implements OnInit {
filteredBranches$!: Observable<Branch[]>;
filteredBranches!: Branch[];
constructor(private route: ActivatedRoute, private branchesService: BranchesService) {
}
activeTab: string=''
ngOnInit(): void {
this.route.paramMap.pipe(
switchMap((params: Params) => {return this.branchesService.getDepBranches(params['get']('dep')) })
).subscribe((branches) => {this.filteredBranches = branches; this.activeTab=this.filteredBranches[0].name});
}
}
and branch.component.html:
<nav mat-tab-nav-bar>
<a mat-tab-link *ngFor="let br of filteredBranches"
[routerLink]="['coursesList', br.code]"
routerLinkActive="activeLink"
(click)="activeTab = br.name"
[active]="activeTab == br.name"> {{ br.name }} </a>
</nav>
<router-outlet></router-outlet>
but, although links of branches are listed in template of branches.component, no courses respect to each branches are shown by coursesList.component which placed in router-outlet of branches.component, because it does not received any route parameter from branch.component, until one of branch link is clicked.
I expect that upon branches links are shown at the same time branches.component is loaded, bellow of them, the courses of the first branch are listed by coursesList.component placed in router-outlet of branches.component.
Whereas no one of branch links is clicked and no parameter passed to coursesList.component, nothing is shown. Therefore, is there a solution to active the first branch link as defualt and pass its courses parameters to coursesList component upon branches.component is loaded? Best regards.
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' }
I was building a new angular (v6.0.1) application and wanted to start wiring it up to handle data through a service. I created a new provider as below:
#Injectable({
providedIn: 'root',
})
export class NewsRepositoryProvider {
constructor(private firebase: AngularFireDatabase) {
}
///Gets a news article starting at a certain index and then so many forward
public getPagedNews(start: number, count: number): AngularFireList<any> {
return this.firebase.list('/News/');
}
}
Wanting to make certain this stub worked before I really dived into it, I wired it up and added it to a component constructor:
AppModule:
#NgModule({
declarations: [
AppComponent,
NavMenuComponent,
NewsComponent,
HomeComponent,
ContactComponent,
ProductsComponent,
ApplicationsComponent,
NewsRepositoryProvider,
],
imports: [
CommonModule,
HttpModule,
FormsModule,
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'applications', component: ApplicationsComponent },
{ path: 'contact', component: ContactComponent },
{ path: 'news', component: NewsComponent },
{ path: 'products', component: ProductsComponent },
{ path: '**', redirectTo: 'home' }
]),
AngularFireModule.initializeApp(FIREBASE_CONFIG),
AngularFireAuthModule,
AngularFireDatabaseModule,
],
})
export class AppModuleShared {
}
Component:
constructor(private newsRepo: NewsRepositoryProvider) {
console.log(newsRepo.getPagedNews(0, 10));
}
I run webpack and then launch the page. To my surprise I get the following error:
An unhandled exception occurred while processing the request.
NodeInvocationException: StaticInjectorError(e)[LocationStrategy -> PlatformLocation]:
StaticInjectorError(Platform: core)[LocationStrategy -> PlatformLocation -> InjectionToken DocumentToken]:
Right-hand side of 'instanceof' is not an object
TypeError: StaticInjectorError(e)[LocationStrategy -> PlatformLocation]:
StaticInjectorError(Platform: core)[LocationStrategy -> PlatformLocation -> InjectionToken DocumentToken]:
Right-hand side of 'instanceof' is not an object
at bt (\ClientApp\dist\main-server.js:109:67471)
I've been pouring over StackOverflow questions, trying to determine what could be the root cause of this error. Anyone familiar with the error? Did I do something wrong in setting up the service?
Angular version 6 comes with new way to inject your service for the tree shaking feature so you can use the old one with is add it to the provider array inside your module like this:
providers: [
NewsRepositoryProvider
]
Or inside the service class like this:
#Injectable({
providedIn: 'root',
})
So you should use one of them and i suggest using the way inside your service.
I was trying to navigate from a parent component (Core) using an url dynamically emitted from a child component (Menubar).
The problem is that the navigation is cancelled without any reason.
To find out if the problem came from the parent component, I implemented a button in the parent component navigating to a static url, and it worked!
Core template:
<app-menubar (onNavigation)="onMenubarNavigation($event)"></app-menubar>
<button type="button" (click)="navigate()">Navigate</button>
<router-outlet><router-outlet>
Core component:
onMenubarNavigation(urlSegments: string[]): void {
this.router.navigate(urlSegments);
}
navigate(): void {
let segments: string[];
segments = ['index', 'messages'];
this.router.navigate(segments);
}
Menubar template:
<a (click)="changeRoute(element.module.route)">
// element.module route is the string: "/messages"
Menubar component:
#Output() onNavigation = new EventEmitter<string[]>();
changeRoute(url: string): void {
let urlSegments: string[];
urlSegments = url.split('/');
urlSegments[0] = 'index';
this.onNavigation.emit(urlSegments);
}
App routing module:
const routes: Routes = [
{ path: 'login', loadChildren: '.\/auth\/auth.module#AuthModule' },
{ path: 'logout', loadChildren: '.\/auth\/auth.module#AuthModule' },
{ path: '', loadChildren: './theme/core/app.core.module#AppCoreModule', pathMatch: 'full' },
];
#NgModule({
imports: [RouterModule.forRoot(routes, { enableTracing: true })],
exports: [RouterModule]
})
export class AppRoutingModule { }
Core routing module:
const coreRoutes: Routes = [
{
path: '',
component: AppCoreComponent,
canActivate: [AuthGuard],
children: [
{
path: 'home',
loadChildren: '..\/home\/app.home.module#AppHomeModule'
},
{
path: 'index',
loadChildren: '..\/index\/app.index.module#AppIndexModule'
},
{
path: '',
redirectTo: 'index',
pathMatch: 'full'
}
]
}
];
#NgModule({
imports: [
RouterModule.forChild(coreRoutes)
],
exports: [
RouterModule
]
})
export class AppCoreRoutingModule {}
The angular routing debug shows that both urls are the same during navigation, using the one emitted by the child component or the static one, but when I navigate using the one emitted, the navigation is cancelled and I have no idea why...
Has someone ever encoutered this kind of trouble with the angular router?
I've followed the instructions in the docs in:
https://www.primefaces.org/primeng/#/menubar
In my module file i've imported the correct lib:
import {MenubarModule,MenuItem} from 'primeng/primeng';
Then in my template I've defined:
<p-menubar [model]="items">
<button pButton label="Logout" icon="fa-sign-out"></button>
</p-menubar>
However, the button is not rendered in html result. Have I messed somewhere?
Best Regards.
imports: [
BrowserModule,
HttpModule,
DataTableModule,
SharedModule,
ButtonModule,
MenubarModule,
RouterModule.forRoot([
{
path: 'home',
component: HomeComponent
},
{
path: 'login',
component: LoginComponent
}, {
path: '',
redirectTo: '/login',
pathMatch: 'full'
},
])
],
The documentation is refering to the 4.1 RC3 version, was using RC2 at the time:
https://forum.primefaces.org/viewtopic.php?f=35&t=51618