angular - 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
函数后,所有本地化字符串都将被加载,我只想在模块加载时加载这些字符串。之后,该模块的所有组件都需要检查这些字符串是否已加载以继续渲染。
解决方案
当一个模块被加载时,它的构造函数被调用。
因此,您可以创建一个 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 }
}
];
推荐阅读
- javascript - 引导程序
- python - 有谁知道为什么我在尝试使用 pip 时会出错?我刚刚下载了最新版本的python,但它无法正常工作
- sql-server - SnowFlake 函数不返回数据和错误
- visual-studio - 如何修复为 Stimulsoft.Reports.Engine.NetCore 检测到的 NuGet 错误版本冲突
- database - 如何打开oracle数据库?
- python - 根据条件连接熊猫中的行
- tensorflow - 关于 Tensorflow 扩展 BigQuery 作为 ExampleGen 的问题
- python - Airflow PythonVirtualOperator 用简单的例子抛出错误
- amazon-web-services - Route 53 配置 S3 url
- react-native - 我想使用在渲染之前初始化的组件生命周期方法