#Destroy component

2 messages · Page 1 of 1 (latest)

prime flare
#

Hello. I want to destroy component but it says 'Property 'getAnnualDays$' has no initializer and is not definitely assigned in the constructor.'
In Ts I have:

  data: User[] = []
  displayedColumns: string[] = ['annualDays','annualDaysTaken', 'annualDaysRemaining','reportedAnnualDays',
    'casualDaysTaken','casualDaysRemaining','casualDays', 'year'];
  getAnnualDays$: Subscription;

  constructor(private backendApiService: BackendApiService) {}


  ngOnInit() {
  const getAnnualDays$ =  this.backendApiService.getAnnualDays(2022).subscribe((value) => {
      this.data = value as any;
      return this.data.values()
    })
  }
  ngOnDestroy() {
    this.getAnnualDays$.unsubscribe();
  }
}```
How should it be? Thank you
stone tapir
#

First, rename your variable without a $ suffix. The $ suffix is conventionally used for observables. And your variable is not an observable, it's a subscription. Calling a variable with a verb is also a bit strange. We usually use verbes for methods.
Second, don't use any. You're shooting yourself in the foot. Use proper, correct types.
Third, realize that the line return this.data.values() doesn't serve any purpose. I don't know what you intend to acheve by returning from the subscribe callback, which is supposed to return void.
Now, to your question: it would probably better to not subscribe in the first place, and instead use the async pipe, which would automatically unsubscribe. But if you really want to subscribe, then either

  • do it in the constructor, so that TypeScript knows that getAnnualDays$ is indeed always initialized
  • or type your variable correctly, since its value can indeed be undefined before ngOnInit has been called, using getAnnualDays: Subscription | undefined or getAnnualDays?: Subscription
  • or tell TypeScript that OK, it can indeed be undefined, but trust me, when I use it, it will never be, so treat is a never undefined, using getAnnualDays?: Subscription