0

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 { }
atiyar
  • 7,762
  • 6
  • 34
  • 75

1 Answers1

1

I would suggest you remove UserProfileService from providers, but make sure you have providedIn: 'root' set. Also make sure you don't provide it anywhere else. This will make sure only one instance of the service will exist, so data should be available.

Also, guard is not a service (PostAuthGuardService), I would rename them if I were you.

Bojan Kogoj
  • 5,321
  • 3
  • 35
  • 57