How to subscribe to an observable from a SessionStorage

Viewed 97

In an Angular component (FirstComponent), I call a service, from which I get an object as a response.I store the response in the browser in a "sessionStorage".

sessionStorage.setItem("data", JSON.stringify(response));

Now, in another component (SecondComponent), I get the "sessionStorage", and paint the results into a Datagrid from an internal component library.

let response = JSON.parse(sessionStorage.getItem("data"));

When calling a component library method with which you can load the Datagrid columns, it gives me the following error:

Concrete line error:

columnsOptions[5].visible = false

core.js:6210 ERROR TypeError: Cannot read properties of undefined (reading '5')
    at TasksContainerComponent.addView (tasks-container.component.ts:144:21)
    at TasksContainerComponent.getScheduleTasks (tasks-container.component.ts:118:16)
    at SafeSubscriber._next (tasks-container.component.ts:52:12)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:183:1)
    at SafeSubscriber.next (Subscriber.js:122:1)
    at Subscriber._next (Subscriber.js:72:1)
    at Subscriber.next (Subscriber.js:49:1)
    at MapSubscriber._next (map.js:35:1)
    at MapSubscriber.next (Subscriber.js:49:1)
    at BehaviorSubject._subscribe (BehaviorSubject.js:14:1)

I get the response from the service of the first component correctly in the second component with "SessionStorage", but it gives me the indicated error. The funny thing is that, if I call the same service of the first component in the second component without using "SessionStorage", I get returns the same response, and everything works perfectly.

It's like I have to create a "sessionStorage" observable and subscribe to load the data correctly, but so far I haven't figured out how to do that.

To optimize, I would like to call the service only once, since in both components I need the same response to paint the data.

This is the second component's OnInit event and this is the error it shows me when I use "SessionStorage", the "columnsOptions" constant is not defined, however if I don't use "SessionStorage" and launch the "columnsOptions" service call, it has the value I need and it works fine.

The objective is to paint the Datagrid with the object stored in "SessionStorage", but I hide a column of the Datagrid in case it has "0" errors, if the "hasErrors" parameter contains 0, it is that I haven't errors and I must hide the last Datagrid column, this is the code that fails exclusively when I try to hide the column:

const columnsOptions: DatagridColumnOptions[] = this.dg.columns?.map(column => ({
  column: column,
  visible: true,
  level: 0,
}));

if (hasErrors === 0) { 
  columnsOptions[5].visible = false;
}

The error is on this line:

columnsOptions[5].visible = false;

But it is because:

columnsOptions = undefined;

What I can do?

0 Answers
Related