Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing router fragment in Angular 6

Tags:

angular

ngrx

I have an angular app, using Angular 6 and NgRX 6.

I have an identity server I am talking to via the implicit flow, that once redirects back to my app, has my token response and so on still in the navigation bar.

I would like to clear that fragment from the url and remain on my route.

For example

http://foo.com/bar/boo#key=value

I would like to clear this once I am finished and be left on

http://foo.com/bar/boo

I am handling this in an effect, as follows

 @Effect({ dispatch: false })
  persistSessionTokens$: Observable<void> = this.actions$.pipe(
    ofType<ActionWithPayload>(SET_SESSION_TOKENS),
    map(action => action.payload),
    tap(tokens => {
      persist(ID_TOKEN_STORAGE_KEY, tokens[ID_TOKEN_STORAGE_KEY]);
      persist(ACCESS_TOKEN_STORAGE_KEY, tokens[ACCESS_TOKEN_STORAGE_KEY]);

      const url = this.router.url;

      this.router.navigate([url], { replaceUrl: true });
    }),
    catchError(error => of({ type: SET_TOKEN_FAILURE, payload: error }))
  );

However this redirects me to http://foo.com/bar/

My application in this case has a base href of bar

boo is the name of my tenant, so it is important I retain this structure in the url.

like image 556
Harry Blue Avatar asked Dec 24 '22 06:12

Harry Blue


1 Answers

You can use Location class from @angular/common. Here is the example:

// This will give you current location path without including hash
// path(includeHash: boolean = false): string
const pathWithoutHash = this.location.path(false); 

// This changes the browsers URL to the normalized 
// version of the given URL, and replaces the 
// top item on the platform's history stack.
// replaceState(path: string, query: string = '', state: any = null): void
this.location.replaceState(pathWithoutHash);

For more about Location

like image 100
Efe Avatar answered Jan 11 '23 23:01

Efe