Let's simplify the question. Say the angular application only has a few components. In app component html,
<app-nav></app-nav>
<router-outlet></router-outlet>
The ts file we inject a service to get navigation menu. The service contains a BehaviourSubject to handle menu items.
@Injectable({
providendIn: 'root'
})
export class AppService {
public items = new BehaviourSubject<Item[]>([]);
public getMenu() {
return this.http.get<Item[]>(this.url);
}
public getItems() {
return this.items.value;
}
}
In app component ts file.
ngOnInit() {
this.service.getMenu().subscribe(
res => {
this.items = res;
this.service.items.next(this.items);
});
}
So far so good. Then in my nav component I can receive the items.
export class NavComponent implements OnInit {
items: any;
constructor(private service: AppService){}
ngOnInit() {
this.items = this.service.getItems();
}
}
Then in Nav html I have
<span *ngFor="let item of items">
<div>{{item.name}}</div>
</span>
So the normal step is to go to http://localhost:4200 then navigation bar is displayed correctly. However if I type the url of another component directly. Say
http://localhost:4200/app/one
It seems the page loads component one
first. The navigation bar is rendered before get the menu items. Actually I log the items in component one, it is empty. Eventually it also goes to app component but it is too late.
So my question is that I want to get menu items in the very first place. Whatever I typed any url I can always get the navbar menu items and rendered correctly. I doubt that I used BehaviouSubject
wrongly. Any hint?