0
votes

I have a similar question to angular router-outlet load before header component, how to prevent?... I have a service locationService.ts, a headerComponent that import and inject the service and set values to an object defined in locationService...locationService.locationStatus. I also have a homeComponent that import and inject locationService. However locationService is undefined when console.log it from the constructor on ngOnInit. I need the examine the value set in the header before I display the html...I am using *ngIf to turn on/off a div in home.component.html depending on the value set in headerComponent. My structure is like this:

app.compnent.html

<custom-header></custom-header>

<router-outlet></router-outlet>

<custom-footer></custom-footer>

header.component.ts

....
...
import { LocationService } from '../locations/locations';
....
....
constructor(
   .....
    public locationService: LocationService,
   ......){
           this.setLocationStatus()
         }

.....
.....
setLocationStatus(){
       this.locationService.getStatus((data) => {
       .....
       ....
       this.locationService.locationStatus = data.status
       .....
       ...
     }

home.component.ts

.....
 import { LocationService } from '../locations/locations';
    ....
    ....

    activeLocation: boolean = false;
    constructor(
       .....
        public locationService: LocationService,
       ......){
         console.log(this.locationService.locationStatus)  <<<<< undefined
              }
     ngOinit(){
              this.activeLocation =
              this.locationService.locationStatus <<<<<undefined error
             }

It appears that the homeComponent is executed before the headerComponent?? If this is so how can I achieve what i need to do which is the have the value set in the header and access it the homeComponent....Is there an alternate way to do this.

1

1 Answers

0
votes

It is really very simple. router-outlet are loaded with the components via the router and then the rest of the components are loaded as they are required by the current template (decided by the give route).

if you need something to be decided before you reach to particular component (route) you should be using the route resolvers. and in that resolver you can inject the service you are trying to initiate in the header component. at the same time you can return the data / which you want to use as a deciding factor for *ngIf.

Please read more about Angular Resolvers here