Based on my research i found some code that worked or at least I thought so. I am using angular 11 and need to capture the previous url so I can route back to it. The below code gets the previous url most of the time but not always, and I set it as a variable. But then when user clicks the back error and calls my goBack function it goes always to my /home which is set as the default route if routes don't exist. So since i seem to get the prev route there mist be something in my code that resets the previousUrl as an empty string and prevents it to work. Do I need to filter additional events to prevent this from happening ?
import {Component, OnDestroy, OnInit} from '@angular/core';
import {ActivatedRoute, Router, RoutesRecognized} from '@angular/router';
import {map, takeWhile} from 'rxjs/operators';
import {ToasterService} from 'angular2-toaster';
import {Location} from '@angular/common';
import {Base64Service} from '../../../../../services/base64.service';
import {FarmService} from '../../../../../services/farm/farm.service';
import {IFarmMaster} from '../../../../../models/farm';
import {Observable} from 'rxjs';
import { filter, pairwise } from 'rxjs/operators';
@Component({
selector: 'app-farm-master-wrapper',
templateUrl: './farm-master-wrapper.component.html',
styleUrls: ['./farm-master-wrapper.component.scss'],
})
export class FarmMasterWrapperComponent implements OnInit, OnDestroy {
farm: IFarmMaster;
private state$: Observable<object>;
alive = true;
previousUrl: string = "";
constructor(
protected route: ActivatedRoute,
private farmService: FarmService,
private toasterService: ToasterService,
private base64Service: Base64Service,
private location: Location,
private router: Router,
) {
}
ngOnInit() {
this.farm = this.route.snapshot.data.farmMaster;
this.farm.DocId = this.route.snapshot.data.farmMaster.DocId;
this.state$ = this.route.paramMap.pipe(
map(() => window.history.state)
);
this.router.events
.pipe(filter((evt: any) => evt instanceof RoutesRecognized), pairwise())
.subscribe((events: RoutesRecognized[]) => {
this.previousUrl = events[0].urlAfterRedirects;
console.log('previous url', this.previousUrl);
})
}
refreshFarm(DocId: string) {
console.log('Reload Farm :' + DocId)
this.farmService.farmMaster(DocId).subscribe((response) => {
this.farm.Record = response.Record;
this.farm.DocId = response.DocId
console.log(response);
})
}
goBack() {
// this.location.back();
// TODO: Fix the back button to show highlight on previous selection
console.log('Will Route back to : ' + this.previousUrl)
this.state$
.pipe(
takeWhile(_ => this.alive),
)
.subscribe(state => {
this.router.navigateByUrl(this.previousUrl, {state});
});
}