I have a problem related to dependency injection. I am new to Angular, the problem is that, I tried to store the logged-in user data in service and call this service in the app component that gets logged in user information from API.
The data from this service is available when I try to access it from /dashboard/*
any descendant links. But when I try to access this data from /dashboard
I got undefined
.
The problem that I have observed is that, data from service does not get loaded until there is a change in the URL. When there is a navigation, data get loaded.
The service is registered in providers of app.module
.
app.module
-
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { UserProfileService } from './services/profile/user-profile.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
DashboardModule,
SharedModule,
BrowserAnimationsModule,
MobileScreenModule,
AuthModule,
JwtModule
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
UserProfileService
],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing.module
-
const routes: Routes = [
// {path: 'auth' , redirectTo:'/auth/login'},
{
path: 'auth',
loadChildren: ()=> import('./auth/auth.module').then(child => child.AuthModule),
canActivate: [PreAuthGuardService]
},
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [PostAuthGuardService],
loadChildren: () => import('./dashboard/dashboard.module').then((childrens) => childrens.DashboardModule)
},
{ path: '**', redirectTo: '/auth/login' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }