My current issue seems to be related to asynchronous programming, specifically with the subscription
not running at the desired time. I typically approach this problem from both the user's and developer's perspectives.
User's Perspective:
When a user is on the home page and clicks on the Home navigation button, the website refreshes. This behavior is not ideal for the user, who expects that clicking on the home page while already on it should have no effect. A visual representation of the navigation can be seen below. On the other hand, if the user is on any other page and clicks on the home page, they should be redirected back to the home page. https://i.sstatic.net/N01os.png
Developer's Perspective:
Upon initializing the template, the code will verify if the router URL is /en/home
. If it matches, the href should be set to #
; otherwise, it should be /en/home
. The commented code snippet below illustrates this logic.
Miscellaneous Service:
// This service performs various tasks, including detecting url changes
@Injectable({
providedIn: 'root'
})
export class MiscellaneousService {
urlChange = new Subject<string>()
// Other properties & methods
}
Header TS Component:
export class HomeHeaderComponent implements OnInit {
currentURL: string = ''
isHomeRoute: boolean = true
constructor(private misService: MiscellaneousService, private router: Router) {}
ngOnInit(): void {
/*
IMPORTANT READ:
We use 'urlChange.next()' on every page to update the currentURL.
While 'this.misService.urlChange.next(this.router.url)' should work,
the subscription does not. It seems to be due to the asynchronous nature
of subscribe. How can this be resolved so that the component always reflects
the current URL?
*/
this.misService.urlChange.next(this.router.url)
this.misService.urlChange.subscribe(currentURL => {
this.currentURL = currentURL
})
console.log(this.currentURL)
if (this.currentURL == '/en/home') {
this.isHomeRoute = true
}
else {
this.isHomeRoute = false
}
}
How can we ensure that we effectively subscribe to any changes in the router.url
? What modifications are necessary?
For further clarification, here is a portion of the template containing the header:
Header Template:
<a class="nav-link" [href]="isHomeRoute ? '#' : '/en/home'">
home<span class="sr-only">(current)</span>
</a>
<!-- More code... -->