在 Angular 16 以上版本中,使用 Standalone Component 時,針對不同的注入需求,可以採取以下策略來解決注入重複性過高的問題: --- ### **1. 所有頁面都需要注入** 如果某個服務或模組是所有頁面都需要的,應該將其放在應用程式的根層級,確保它只被注入一次,並且可以被全域使用。 #### 解決方法: - **使用 `providers` 在 `bootstrapApplication` 中全域註冊服務**: 在 `main.ts` 中,將需要的服務加入 `providers` 陣列,這樣可以避免在每個 Standalone Component 中重複注入。 ```typescript import { bootstrapApplication } from '@angular/platform-browser'; import { AppComponent } from './app/app.component'; import { provideHttpClient } from '@angular/common/http'; import { SomeGlobalService } from './services/some-global.service'; bootstrapApplication(AppComponent, { providers: [ provideHttpClient(), // 全域提供 HttpClient SomeGlobalService // 全域提供服務 ] }).catch(err => console.error(err)); ``` 這樣,`SomeGlobalService` 就會在所有頁面中可用,而不需要在每個 Standalone Component 中重複注入。 --- ### **2. 大多數頁面需要注入** 如果某個服務或模組是大多數頁面需要的,但不是所有頁面都需要,則可以考慮將這些服務集中在一個共享模組或共享 Standalone Component 中,並在需要的頁面中匯入。 #### 解決方法: - **建立共享的 Standalone Component 或模組**: 將這些服務集中在一個共享的 Standalone Component 中,並在需要的頁面中匯入。 ```typescript import { EnvironmentService } from './services/environment.service'; import { provideHttpClient } from '@angular/common/http'; export const SHARED_PROVIDERS = [ provideHttpClient(), EnvironmentService ]; ``` 在需要的頁面中匯入這些共享的 providers: ```typescript import { Component } from '@angular/core'; import { SHARED_PROVIDERS } from '../../shared/shared-providers'; @Component({ selector: 'app-example-page', standalone: true, templateUrl: './example-page.component.html', styleUrls: ['./example-page.component.css'], providers: [...SHARED_PROVIDERS] // 匯入共享的 providers }) export class ExamplePageComponent {} ``` 這樣可以避免在每個頁面中手動注入相同的服務。 --- ### **3. 只有部分頁面或單一頁面需要注入** 這種情況下,直接在需要的 Standalone Component 中使用 `providers` 注入即可,這樣可以確保服務的作用域僅限於該頁面。 #### 解決方法: - **直接在 Standalone Component 中注入**: ```typescript import { Component } from '@angular/core'; import { SpecificService } from '../../services/specific.service'; @Component({ selector: 'app-specific-page', standalone: true, templateUrl: './specific-page.component.html', styleUrls: ['./specific-page.component.css'], providers: [SpecificService] // 僅在此頁面提供服務 }) export class SpecificPageComponent {} ``` 這樣可以確保服務的作用域僅限於該頁面,避免不必要的全域注入。 --- ### **總結** - **所有頁面需要注入**:在 `bootstrapApplication` 中全域註冊服務。 - **大多數頁面需要注入**:建立共享的 `providers` 或共享的 Standalone Component。 - **部分頁面或單一頁面需要注入**:直接在該 Standalone Component 中使用 `providers`。 這樣可以有效地管理服務的作用域,避免重複注入的問題,同時保持程式碼的清晰與可維護性。
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up