Home > Mobile >  How to pass non-string objects between routes in Angular?
How to pass non-string objects between routes in Angular?

Time:11-14

I am building a file viewer. For this, I have a component called FileBrowserComponent which is displayed when the route is called /files.

I attach a query param when navigating in order to display the content of a directory. So to open a specific directory, I call Router.navigate with `/files?location=c:/users/xyz/...'.

Inside the component, I subscribe to ActivatedRoute.queryParam, which means whenever the component is active I get notified when the user browses to another location and I can then display the files and folders.

In one case I need to pass an optional non-string object to the URL. But I subscribe only to the queryParams object that gives me the Params as a string.

What other object can I subscribe to, that triggers a callback whenever I navigate to that route that gives me back the query params including the custom object?

CodePudding user response:

First of all, consider passing the id and then regetting the object from a remote endpoint.

If that is something that can't be applied to your situation then create a subject that holds the state:

(note this is a const that is declared outside of a class)

export const someRouteParams$ = new BehaviorSubject<YourObjectTypeHere>({...your defaults here });

For which you later send the object that you want to pass:

someRouteParams$.next({ ...your passed object });

and eventually subscribe in your sub component:

someRouteParams$.subscribe(someObject => {
    console.log(someObject);
});

Alternatively, get a state management library like NGXS, Akita or NGRX to manage this state for you

  • Related