Search code examples
angularroutesnavigation

How to get the value outside the subscription?


I want to get the previous route and print it's value in the HTML file. But nothing is getting printed. The value is still null outside the subscription.

This is my code snippet:

TS file:

 @Component({
  selector: 'app-transaction-details-payments',
  templateUrl: './transaction-details.component.html',
  styleUrls: ['./transaction-details.component.css']
})
 previousUrl: any = null;

ngOnInit(){
    this.router.events.pipe(
          filter((event) => event instanceof NavigationEnd)
        ).subscribe((event: NavigationEnd) => {
          this.previousUrl = this.currentUrl;
          this.currentUrl = event.url;
          this.urlService.setPreviousUrl(this.previousUrl);
 
this.getPrevUrl();
        });
    }

getPrevUrl(){
    console.log(this.previousUrl) //getting the correct value but this value is not getting printed in HTML.
}

HTML code:

<p>{{previousUrl}}</p>

Solution

  • I've tried creating a service and moved my code to the service and used it inside my component and it worked.

    Here is my code:

    Service:

     @Injectable({
          providedIn: 'root'
        })
    export class UrlService {
      private previousUrlUpdated: string;
      private currentUrl: string;
    
      constructor(private router: Router) {
        this.currentUrl = this.router.url;
        router.events.subscribe(event => {
          if (event instanceof NavigationEnd) {
            console.log(event)
            this.previousUrlUpdated = this.currentUrl;
            this.currentUrl = event.url;
          };
        });
      }
    
      public getPreviousUrl() {
        return this.previousUrlUpdated;
      }
    }
    

    ts:

    this.previousUrl = this.urlService.getPreviousUrl();