首页 > 解决方案 > Angular如何在渲染组件之前检查模块是否加载

问题描述

我的 Angular 应用程序有一些模块,它们是延迟加载的。在模块 A 的一个组件中,我想在使用*ngIf. 我怎样才能做到这一点?谢谢你。

更新 1。

export class CustomerManModule extends AppModuleBase {
  constructor(injector: Injector) {
    super(injector, AppConsts.module.customerMan);

    var localeName = locale();
    this.appService.getLanguage(localeName, AppConsts.module.customerMan).subscribe((messages: any) => {
      let language = new Object();
      language[localeName] = messages;
      loadMessages(language);
    })
  }
}

调用loadMessages函数后,所有本地化字符串都将被加载,我只想在模块加载时加载这些字符串。之后,该模块的所有组件都需要检查这些字符串是否已加载以继续渲染。

标签: angulartypescript

解决方案


当一个模块被加载时,它的构造函数被调用。

因此,您可以创建一个 custom ModuleStateService,将其注入模块的构造函数并跟踪其状态。

例子:

@NgModule({
  imports: [CommonModule, SharedServicesModule],
  declarations: [LoginComponent]
})
export class AuthModule {
  constructor(moduleStateService: ModuleStateService) {
    console.log('AuthModule loaded');
    
    moduleStateService.loadedModule('AuthModule');
  }
}

更新 抱歉更新晚了。

您可以将 Route Resolver 与使用一些简单缓存机制的服务结合使用,例如shareReplay(1)请求只发出一次。

//Resolver

@Injectable({
  providedIn: 'root'
})
export class LocalizationResolver implements Resolve<Observable<any>> {
  constructor(private languageService: LanguageService) {}

  resolve(): Observable<any> {
    return this.languageService.loadMessages();
  }
}
// Service, with simplified caching

@Injectable({
  providedIn: 'root'
})
export class LanguageService {
  private cache = {};
  private url = 'https://api.github.com/users';

  constructor(private http: HttpClient) {}

  loadMessages(): Observable<any> {
    if (this.cache['messages']) {
      return this.cache['messages'];
    }
    this.cache['messages'] = this.http.get(this.url).pipe(shareReplay(1)); // todo error handling
    return this.cache['messages'];
  }
}
// Route configuration:

const ROUTES = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: ContainerComponent },
   ...
  {
    path: 'resolver',
    component: WithResolverComponent,
    resolve: { users: LocalizationResolver }
  }
];

堆栈闪电战


推荐阅读