0

I want to encrypt query params URL in Angular.

my URL now looks like this: https://example.com/posts/235645?asc=1&published=true

what I want to approach is to see the previous URL like: https://example.com/posts/ksjz654fezf?asc=sfeui54sf&published=eirjh54561

but in condition when I'll use the this.activatedRoute.queryParams.subscribe(params => {}) I want to see the parameters I have from the pushed observable like it was in the first URL to use in the API call.

  • which class or package do you think it's going to help me out?

I've used the functions (btoa, atoa) in ngOnInit() to encrypt/decrypt. but I have a large app so it's not the best solution to approach what I want. also, I find it bad practice to add the code in many components classes.

I appreciate your help and time.

Thanks

CoderNadir

CoderNadir
  • 11
  • 3

1 Answers1

1

I suggest this version. I am using on route events to encrypt and decrypt queryParams.

   router.events
          .pipe(filter(event => event instanceof NavigationStart))
          .subscribe((event) => {
            const urlSplitted = (event as NavigationStart).url.split('?q=');
            const basePart = urlSplitted[0];
            let queryParamPartDecrypt = '';
            if (urlSplitted.length > 1) {
              queryParamPartDecrypt = decodeURI(this.decode(urlSplitted[1]));
              router.navigateByUrl(`${basePart}?${queryParamPartDecrypt}`);
            }
          });
    
        router.events
          .pipe(filter(event => event instanceof ActivationEnd))
          .subscribe((event) => {
            const urlSplitted = router.url.split('?');
            const basePart = urlSplitted[0];
            const queryParamPart = urlSplitted.length > 1 ? urlSplitted[1] : null;
    
            let queryParamPartCrypt = '';
            if (queryParamPart) {
              queryParamPartCrypt = `?q=${this.encode(queryParamPart)}`;
            }
            this._location.go(`${basePart}${queryParamPartCrypt}`);
          });
      }
    
    
      encrypt(url: string): string {
        /** code of encrypt**/
        return base16String;
      }
    
      decrypt(base16String: string): string {
        /** code of decrypt **/
        return url;
      }
    }
  
Pythe
  • 11
  • 3
  • thanks for the answer brother good approach! I've solved it with another way. I'll post it later once I have the time, because I want to post it as a (medium - dev) articles to better clarify things, again I appreciate it a lot :) – CoderNadir Mar 29 '23 at 16:28
  • I am looking forward to your article. Don't forget to share it here. – Pythe Mar 30 '23 at 17:52
  • yes sure I'll add the link here too, thanks for your interest! – CoderNadir Mar 30 '23 at 18:01