Created an Angular Provider and now getting StaticInjectorError - javascript

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.

Related

Angular 8 ERROR in Cannot read property 'loadChildren' of null

I have ERROR in Cannot read property 'loadChildren' of null on npm run build prod --aot=true in my Angular 8 project. The local build works perfect.
I found, that this error appears when I'm trying to convert some object to Route by a special function, and after that add this route to Routes array.
Please help to understand how to fix it.
Some piece of code:
function objToRoute(obj: any): Route {
// convert it to route and return
}
const routes: Routes = [
path: '',
component: SomeComponent,
children: [
objToRoute(specialObject),
{
path: '**',
component: StubComponent
}
]
]
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class SomeRoutingModule {}
To be more specific, here is a simple example of objToRoute function:
function objToRoute(obj: any): Route {
return obj;
}
const routeObj: Route = {
path: 'somePath',
pathMatch: 'full',
loadChildren: () => import('pathToDir/someLazy.module').then(m => m.SomeLazyModule)
}
const routes: Routes = [
path: '',
component: SomeComponent,
children: [
objToRoute(routeObj),
{
path: '**',
component: StubComponent
}
]
]
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class SomeRoutingModule {}
And in this case I have the error ERROR in Cannot read property 'loadChildren' of undefined on npm run build prod --aot=true

How to change router paths programmatically?

I'm building a Ionic app using Angular and calling an API to get some results. According to a particular property of the response object (such as "mode"="0" or mode="1" I need to change paths defined in app routing module, in particular to dynamically change the home page.
I'd like appcomponent (starting component) to call the API and to check the mode, then passing some routes according to that property.
E.g.:
I'd like to have something like:
if (mydata['mode']==="0") {
this.appRoutes = [
{
path: '',
redirectTo: 'firstPath',
pathMatch: 'full'
},
{
path: 'firstPath',
loadChildren: './firstpath.module#FistPathModule'
},
{
path: 'secondPath',
loadChildren: './secondpath.module#SecondPathModule'
}
]
} else if (my_data['mode']==="1") {
this.appRoutes = [
{
path: '',
redirectTo: 'secondPath',
pathMatch: 'full'
},
{
path: 'secondPath',
loadChildren: './secondpath.module#SecondPathModule'
},
]
}
Is there a way to do something like this inside the app-routing.module?
Hiding firstPath in the second case is possible as well?
This is not a correct way to make changes in app-routing file for such requirement.
You can use Guard to implement this.
In your child route file do like this:
{
path: '',
component: HomePage,
canActivate: [AuthGuard]
}
Auth Guard file:
import { Injectable } from '#angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, CanActivate } from '#angular/router';
#Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
mode: number; **// You can save this mode variable into a common service and use it.**
constructor() { }
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
if(this.mode == 1) {
return false;
}else {
return true;
}
});
}
}

"Error: Arguments array must have arguments." AppModule

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) {
}

Angular 5 http interceptor not intercepting

I've got a correct JWT token stored in local storage and an interceptor that I blatantly copied from a tutorial. However, it doesn't intercept and add headers to requests.
Here's where I make a request:
https://github.com/Marred/Informakcja/blob/master/Informakcja-client/src/app/services/information.service.ts
here's the interceptor:
https://github.com/Marred/Informakcja/blob/master/Informakcja-client/src/app/services/token.interceptor.ts
and my appmodule - I'm pretty sure it's correctly imported:
https://github.com/Marred/Informakcja/blob/master/Informakcja-client/src/app/app.module.ts
When I make a request I expect the interceptor to log messages that I specified to console and add the token to header, it doesn't do that though and I've got no idea why :/ I checked the code with some other tutorials found online and didn't see any differences capable of breaking my code. I also don't have enough experience with Angular to debug it properly.
Any help would be much apprecieated.
You are doing couple of things wrongly here:
Interceptors are used with HttpClientModule not with HttpModule. You are using HttpModule. You need to change to HttpClientModule
Add HttpClientModule in imports array in app.module.ts
Import HttpClient in your authentication.service.ts and take its reference in its constructor.
Refer below code:
//app.module.ts
import { HttpClientModule, HTTP_INTERCEPTORS } from '#angular/common/http';
.
.
.
#NgModule({
declarations: [
AppComponent,
.
.
.
],
imports: [
BrowserModule,
.
.
.,
HttpClientModule, //add here
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'login', component: LoginComponent },
{ path: 'register', component: RegisterComponent },
{ path: 'add-information', component: AddInformationComponent },
{ path: '**', redirectTo: 'home' }
], { useHash: true })
],
providers: [
{ provide: 'BASE_URL', useValue: 'https://some URL/' },
UserService,
InformationService,
AuthenticationService,
AlertService,
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
and
//information.service.ts and authentication.service.ts
import { Injectable, Inject } from '#angular/core';
import { HttpClient} from '#angular/common/http'; //added import
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
#Injectable()
export class InformationService {
constructor(private http: HttpClient, #Inject('BASE_URL') private baseUrl: string) { } //made changes in cunstructor
add(link: string, title: string, description: string) {
return this.http.post(this.baseUrl + 'api/Information', { link: link, title: title, description: description })
.map((response: Response) => {
console.log(response);
});
}
}
make similar changes in authentication.service.ts

Angular 5: Unable to navigate to a dynamic url

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?

Categories