从同一级别访问 Angular 中的应用程序时,来自服务的数据不可用

问题描述

我有一个与依赖注入相关的问题。我是 Angular 的新手,问题是,我试图将登录用户数据存储在服务中,并在从 API 获取登录用户信息的应用组件中调用此服务。

当我尝试从 /dashboard/* 任何后代链接访问该服务时,该服务的数据可用。但是当我尝试从 /dashboard 访问这些数据时,我得到了 undefined

我观察到的问题是,在 URL 发生更改之前,不会加载来自服务的数据。当有导航时,数据被加载。

服务已在 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 { }

解决方法

我建议您从提供程序中删除 UserProfileService,但请确保您已设置 providedIn: 'root'。还要确保您不要在其他任何地方提供它。 这将确保只有一个服务实例存在,因此数据应该可用。

另外,guard 不是服务 (PostAuthGuardService),如果我是你,我会重命名它们。