Issue
I feel like my issue has to do with asynchronous programming as the subscription
is not running when I would like it to. I usually divide my problem into the user's perspective and the developer's perspective.
User's Perspective:
When the user is on the home page and they click on the Home navigation button, then the website refreshes. The user does not find that appealing and wants it for if the user is on the home page and clicks on the home page, then nothing should happen. A picture of the navigation is here below. If the user is outside the home page, then (obviously) if they click on the home page then they should be redirected to the home page.
Developer's Perspective:
During the initialization of the template, the code will check if the router URL is /en/home
. If it is /en/home
then the href should be equal to #
and if it isn't then the href should be equal to /en/home
. Commented code is provided below.
Miscellaneous Service:
// service that does miscellaneous things, one of which is just detecting a url change
@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:
on every page, we will do a 'urlChange.next()' method to ensure the currentURL is updated.
I would suppose that the urlChange.next(this.router.url) works but what I am sure of is that the
subscription does not work as currentURL is always an empty string. I would suppose that this has
to do with the asyncronousity of subscribe and when it runs. If that is the case, how can I fix this so that
the component is always updated to the current URL the user is on?
*/
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
}
}
So how can I make it so the we subscribe to any changes in the router.url
? What do I need to change?
For more reference, here's the part of the template that is the header
Header Template:
<a class="nav-link" [href]="isHomeRoute ? '#' : '/en/home'">
home<span class="sr-only">(current)</span>
</a>
<!-- Other code... -->
Solution
You could observe the router.events
and filter out the NavigationEnd
events to catch all successful routing events.
router.events
.pipe(
// Only take successfull navigation events
filter((routingEvent) => routingEvent instanceof NavigationEnd),
)
.subscribe((routingEvent) => {
// Do anything with the URL at this point
console.log(routingEvent.url);
});
Answered By - NoNamer777
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.