Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform GET request before component initialization

I have template code like this:

 <li *ngIf="isRoot() || isSoftware()">

Also i have this functions in my components code:

isRoot() {
    return this.service.Level == 'Root';
}

isSoftwareOnly() {
    return this.service.ServiceType == 'Software';
}

this.service gets by HTTP request. How can I get request before template starts render? Now isRoot() and isSoftware() always return false, because this.service.Level and this.service.ServiceType are undefined

like image 421
Maksim Koronchik Avatar asked Jun 13 '26 06:06

Maksim Koronchik


1 Answers

I see three ways:

First (quickest): Use constructor of your component (let's say that you have fetchData method in your service to make an http request:

 export class Component {
     constructor(private service: MyService) {
          this.service.fetchData();
     }
 }

Second (slower): Use ngOnInit hook - data will be fetched in the same moment when initialization of view starts.

Third: Use ngOnChanges lifecycle hook (in my opinion this is not best practice in your usecase) - according to documentation:

Respond when Angular (re)sets data-bound input properties. The method receives a SimpleChanges object of current and previous property values. Called before ngOnInit() and whenever one or more data-bound input properties change.

More about lifecycle hooks in Angular.

like image 161
Maciej Treder Avatar answered Jun 15 '26 00:06

Maciej Treder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!