Using Angular2, how to redirect to previous url before login redirect

前端 未结 4 1541
说谎
说谎 2020-12-31 03:29

Using Angular2 to create a single page app, I\'m intercepting unauthenticated user access to non-public routes in a custom RouterOutlet and redirecting them to

4条回答
  •  被撕碎了的回忆
    2020-12-31 04:06

    This worked for me. Inject it into your main App component's constructor having registered it in the bootstrap method. The first val on page load should be the original URL. I am unsubscribing right after to be efficient since I don't (perhaps, yet) want to listen to subsequent router events in this service. Inject the service into other places where originalUrl is needed.

    import { Injectable } from '@angular/core';
    import { Router } from '@angular/router';
    import { Subscription } from 'rxjs/Subscription';
    
    @Injectable()
    export class UrlTrackingService {
    
      public originalUrl: string;
    
      constructor(
        private router: Router
      ) {
        let subscription: Subscription = this.router.events.subscribe((val) => {
          this.originalUrl = val.url;
          subscription.unsubscribe();
        });
      }
    
    }
    

提交回复
热议问题