網站首頁 編程語言 正文
在 Angular 開發中,我們經常遇到一個 NgModule 在導入時需要調用它的靜態 forRoot 方法。,最值得注意的例子是 RouterModule. 當在 Angular 應用的根目錄注冊這個模塊時,導入RouterModule的方式如下:
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: '', redirectTo: '/index', pathMatch: 'full' }
];
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
...
})
export class AppModule { }
這個約定在 ngx-bootstrap
中也使用過,以前在 Angular Material
中也使用過。這種約定意味著,給定的模塊必須在調用 forRoot()方法時,注冊到應用程序的根 NgModule 中。這個方法有什么特別之處,以至于它需要在應用程序的根目錄調用,而不是在其他NgModule中調用?
對于初學者來說,forRoot() 約定返回什么?通常,這個方法的返回類型是一個符合ModuleWithProviders
接口的對象
。這個接口是一個可接受的NgModule導入接口,它有兩個屬性:
interface ModuleWithProviders {
ngModule: Type<any>
providers: Provider[]
}
forRoot() 方法會返回一個 NgModule 及其依賴的提供商。這和根 NgModule 有什么關系?也許什么都沒有。事實上,盡管這種約定意味著它必須在應用的根模塊處導入,但在很多情況下,你可以在非根模塊中導入它,它也能工作。
下面是 ModalModule 在ngx-bootstrap中使用forRoot()約定的方式:
import { NgModule, ModuleWithProviders } from '@angular/core';
import { ModalBackdropComponent } from './modal-backdrop.component';
import { ModalDirective } from './modal.component';
import { PositioningService } from '../positioning';
import { ComponentLoaderFactory } from '../component-loader';
@NgModule({
declarations: [ModalBackdropComponent, ModalDirective],
exports: [ModalBackdropComponent, ModalDirective],
entryComponents: [ModalBackdropComponent]
})
export class ModalModule {
public static forRoot(): ModuleWithProviders {
return {ngModule: ModalModule, providers: [ComponentLoaderFactory, PositioningService]};
}
}
盡管從理論上講,導入forRoot()方法的額外提供程序。在子ngmodule中是可行的,但將它注冊到應用程序的根目錄,在很多方面都有幫助。
首先,考慮 providers 的注入方式與組件和指令有何不同。通常,當用@Injectable裝飾一個類并在NgModule中注冊為提供商時,這個類只創建一次,并且這個實例會在整個應用中共享。當Angular引導根模塊時,所有NgModule中所有可用的導入都會在那時注冊,并對整個應用都可用——它們是全局的。這就是為什么注冊在子NgModule中的提供商在整個應用中都是可用的。
原文鏈接:https://blog.csdn.net/i042416/article/details/125690080
相關推薦
- 2022-08-26 C++?超詳細示例講解list的使用_C 語言
- 2022-06-14 golang連接redis庫及基本操作示例過程_Golang
- 2022-03-15 has been blocked by CORS policy: Response to prefl
- 2023-05-26 shell腳本執行命令自動填充密碼(自動輸入密碼)_linux shell
- 2022-07-13 Linux OS 運行python腳本中smtplib has no attribute SMTP_
- 2023-11-12 jetson nano報錯Cannot allocate memory的問題——解決辦法
- 2022-05-29 Python實現灰色關聯分析與結果可視化的詳細代碼_python
- 2022-06-27 IIS中設置HTTP訪問重定向到HTTPS_win服務器
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支