Angular 2+ Replace the parameter in the URL when changing manually by the user in the adress bar

810 views Asked by At

I have URL which takes three parameters like localhost:4200/website/param1/param2/pagename/param3?user=userid

If the user changes either of the parameters and its not valid , eg: localhost:4200/website/newparam1/newparam2/pagename/param3?user=userid i want to redirect them back to valid url localhost:4200/website/param1/param2/pagename/param3?user=userid

I have created the service to validate and return proper id for all these parameters. so here i am not able to replacing the param's in URL with the right value on load rather than redirect/naviagte.

I have tried to dynamically redirect in component with the below code. this.route.navigate("[relativepath,param1, param2,pagname,configid]",{queryparams})

But this will show the transition from wrong url and to the right one. i want all this to happen on load, like on resolve on route which inturn calls the service.

My service has

  createPram1(): Observable<any> {
    return of(this.parameter1);
  }

  createParam2(param1: string): Observable<any> {
    return of(this.param2);
  }

  validateParam1(id: string): Observable<any> {
    return of(this.param1=== id ? id : this.param1);
  }

  validateParam2(id: string): Observable<any> {
    return of(this.param2=== id ? id : this.param2);
  }

My Resolve.ts

export class AppPathResolve implements Resolve<any> {
  constructor(private Service: Service) { }
  resolve(route: ActivatedRouteSnapshot): Observable<any> {
     const paramOne= route.paramMap.get('param1');
     if (paramOne=== null) {
         return  this.Service.createPram1();
     } else {
         return this.Service.validateParam1(param1);
     }
  }
}

I have searched many links and i the answers dint match my requirement, finally posting it here , hoping to get some info here. thanks in advance!

2

There are 2 answers

5
Parth Shah On

If your redirected URL is not proper while redirecting, use ResponseInterceptor to intercept your request and redirect it to preferred URL.

export class ResponseInterceptor implements HttpInterceptor {

constructor() { }

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const toaster = this.injector.get(ToasterService);
    return next.handle(req)
        .map(response => {
            return response;
        }).catch(exception => {
                switch (exception.status) {
                    case '404': // you can put any status you want
                        toaster.showErrorMessage(any message to display);
                        this.router.navigate([write your preferred path location here]); // this will redirect you to specific URL
                        break;

                }
            return Observable.of(exception);
        });
}

}

8
Ashish Ranjan On

Resolvers are ideally used to fetch some data for the component before it loads. If you want to prevent a user from entering a URL use Route Guards instead.

{path: "website/:param1/:param2/pagename/:param3", component: YourComponent, canActivate: [ParamCheckGuard]}


@Injectable()
export class ParamCheckGuard implements CanActivate {

  constructor(private service: Service, private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
      const paramOne= next.paramMap.get('param1');
      if (paramOne=== null) {
          return  this.service.createPram1().pipe(map((newParam) => {
                        // form a valid URL and navigate()
                        return false
                    })
                  )
      } else {
          return this.service.validateParam1(paramOne).pipe(map((newParam) => {
                       if (paramOne == newParam) {
                          // it is a valid param.
                          return true
                       }
                       // form a valid URL and navigate()
                       return false;
                   })
                 )
      }
  }
}