簡體   English   中英

Angular 將提供程序添加到組件的最佳實踐是什么

[英]Angular what is the best practice for adding providers to component

我構建了一個使用延遲加載的 Angular 應用程序。 在整個應用程序中,如果組件和服務之間存在 1:1 的關系,我的代碼結構如下:

@Injectable()
export class ContactFormService {
    ....stuff...
}

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.scss'],
  providers: [ ContactFormService ]
})
export class ContactComponent {
    ....stuff...
}

如您所見,我直接將服務添加為提供者之一,而不是使用@Injectable({ providedIn: 'root' })

當時我認為這將有助於解決使用 singleton 的任何潛在問題,如果該服務用於不同的組件並失去 1:1 的關系。

我注意到的副作用是,在編寫單元測試時,我必須將overrideComponent()添加到配置中

我必須這樣做(注意:我必須覆蓋提供的服務):

TestBed.configureTestingModule({
   declarations: [ContactComponent]
})
.overrideComponent(ContactComponent, 
   { set: { providers: [{ provide: ContactFormService, useValue: contactFormServiceSpyObj }] }})
.compileComponents();

而不是這個:

await TestBed.configureTestingModule({
  providers: [
    { provide: ContactFormService, useValue: contactFormServiceSpyObj }
  ],
  declarations: [ ContactComponent ]
}).compileComponents();

這讓我想知道我是否遵循了一個非常糟糕的做法? 如果是這樣,什么情況適合以我這樣做的方式注入服務?

我知道@Injectable({ providedIn: 'root' })在構建應用程序時有助於 tress shaking 過程

我看不出你在做什么 - 當我希望它們專用於組件實例(可能還有子實例)時,我也會向組件提供者添加服務。

你應該記得在服務中使用ngOnDestroy方法清理資源。 (是的,angular 在服務上調用ngOnDestroy )。

在一次只顯示一個組件實例的情況下,我更喜歡使用不同的方法來提供組件。 我使用 root 中提供的 singleton 服務,並在組件ngOnInit上調用該服務的初始化方法。 在該方法中,我清理了先前組件實例遺留下來的所有資源。 當我使用單個應用程序范圍的 state 樹並且我不想分別為每個組件生成密鑰時,這真的很方便。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM