The Angular component fails to retrieve data from a subscribed service when the data is being fetched from the sessionStorage

Within my Angular application, there exists a service that handles incoming objects by adding them to a list of objects, then saving the updated array to sessionStorage. This service also sends the updated list to another application that is subscribed to changes. However, an issue arises when the subscribed component does not receive the data from the service after a page refresh. Despite the service successfully retrieving the data from sessionStorage, updating the local array, and dispatching the newly loaded data using next to all subscribers, the subscribed component fails to trigger the subscription.

Here is a snippet of the relevant code:

    //some.service.ts
      private dataSub = new Subject<Data[]>();
      public dataObservable$ = this.dataSub.asObservable();
      private data: Data[] = [];
    .
    .
    .
      constructor() { 
        const data = sessionStorage.getItem("data");
        if(data){
          this.data = JSON.parse(data);
          this.dataSub.next(this.data);
        }
      }
   .
   .
   .
   public someFunction(){
      sessionStorage.setItem("data", JSON.stringify(this.data));
   }

The component subscribing to changes in some.service:

//some.component
private dataSubscription: Subscription = new Subscription();
public data: Data[] = [];
constructor(private someService: SomeService) { }
ngOnInit(): void {
   this.dataSubscription = this.someService.dataObservable$.subscribe(newData => {
  this.data= newData ;
 })
}

Answer №1

The sequence in which Angular will create these classes is as follows: Services first, followed by Components.

If your subject is not returning values (at least by default), the component will receive future values instead of current ones. This is because the subject was instantiated, updated, and then subscribed to. You may consider using a BehaviorSubject or implementing replay functionality in your subject. This way, the component will receive the most recent value upon subscription.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dealing with the challenges posed by middleware such as cookie access and memory leaks

Utilizing express with cookieParser() where my client possesses the cookie named: App.Debug.SourceMaps. I've crafted a middleware as follows: app.get('/embed/*/scripts/bundle-*.js', function(req, res, next) { if (req.cookies['App ...

Is there a way to assign a value to an Angular-specific variable using PHP?

In the development of my Angular 4 application, I encountered an issue while receiving JSON data based on an id value through a PHP script. Upon examining the code, it seems that there should be a value passed into this.PropertiesList. examineProperties(i ...

Bring in a template from a URL using Angular and then compile it within a div

Being a beginner in Angular JS, I am curious about how to load an external template and compile it with specific data into a targeted div. Here is the sample template: <script type="text/ng-template"> <img src="{{Thumb}}" /> <script& ...

Implementing OpenID Connect with Angular Single Page Application and Asp.Net Core 3.1 Backend

I am embarking on a project to develop a cutting-edge (Angular) Single Page Application with a robust (Asp.Net Core) back-end, all while prioritizing security best practices. Here is the blueprint for my plan: The SPA showcases a Login button When the use ...

Using react-hook-form to easily update form data

While working on my project with react-hook-form for updating and creating details, I encountered a problem specifically in the update form. The values were not updating properly as expected. The issue seems to be within the file countryupdate.tsx. import ...

Tips for building a dynamic filter in AngularJS

data = {key:0, Name:"Arun", key:1, Name:"Ajay", key:3, Name:"Ashok"} function dynamicfilter(data, fieldName, filtervalue){ $filter('filter')(data, { fieldName: filtervalue }); } Having trouble implementing a dynamic filter in AngularJS? I&a ...

What is the best way to modify a variable in a nested element using ng-click in the parent element?

Review this code snippet: <section class="page-section about-us" scroll-bookmark="about-us" ng-click="activeSection=true" ng-init="activeSection=false"> <div class="page-content sub-content active-section">{{activeSection}} < ...

Issue encountered while configuring input in ReactJS: the label is conflicting with the input value, causing it to be overwritten when using material.ui components

Hello fellow developers! I am currently facing an issue in my reactJS project. I am using the react-form-hook along with Material-UI's TextField. The problem arises when I input data into a field named cep, triggering a function that fetches content ...

Animated CSS side panel

I'm currently working on creating an animation for a side menu. The animation works perfectly when I open the menu, but the problem arises when I try to animate it back closed. Is there a property that allows the animation to play in reverse when the ...

How can I implement a scroll bar in Angular?

I am facing an issue with my dialog box where the expansion panel on the left side of the column is causing Item 3 to go missing or appear underneath the left column when I expand the last header. I am looking for a solution to add a scroll bar so that it ...

Create a table by incorporating the information from the page along with additional content

I need to extract the data from a list and convert it into a table, add some additional content that I will provide, and then align the table accordingly. While I can easily align elements and already have the list, I am facing difficulty in converting it ...

Are there any risks associated with using nested setTimeout functions with the same name?

While reviewing the source code of typed.js, I noticed that the main function in this plugin utilizes a design pattern with multiple setTimeout functions nested inside one another. Here is a snippet of the code: self.timeout = setTimeout(function() { / ...

What could be causing one of my images to not appear on my Gatsby page?

Hey there, I could use some help with this issue: Recently, I created a website using Gatsby.js and deployed it to my web server (which is running NGINX on Ubuntu 20.04). The site uses Gatsby Image for querying and displaying images, and everything seems t ...

Encountering a CORS issue specifically on the client side of a Next.js application when interacting with an API gateway

I've been struggling with this issue for a week now and can't seem to fully describe it. I have a FastAPI server running as a Lambda connected to API Gateway. https://i.stack.imgur.com/S5Zx9.png Both FastAPI and API Gateway have CORS enabled, b ...

Sending data to back-end server using Multer, Node.js, and Express via a POST request

I have been facing an issue while trying to send a form from my local system to the backend server via a POST request. Every time, it seems to go with --binary-data instead of going with --form. Below is a sample curl command that I am looking to replicat ...

Encountering an unexpected error: receiving a void element tag as input in React

Any ideas on how to resolve the following error message: input is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML` Check out my code snippet below: import "./styles.css"; export default function App() { re ...

Filtering in AngularJS can be done by combining two fields at

I attempted to implement similar code for filtering my tasks, but it seems to be malfunctioning. When I use just one filter, everything works fine regardless of which one I choose. However, when I attempt to filter by the second input, it simply does not w ...

Issues with Loading childComponent in Angular 5 Parent Component

How can I successfully load an internal component, specifically the store-top component at app/stores/store/store-top.component? I want to display the store-top content in the store component when a user clicks on any of the stores from a list. Any sugges ...

display different vue component based on screen size

I am in search of a method to implement responsive components in Vue.js (Nuxt). I have developed this mix-in but encountering an error: export const mediaQuery = { data() { return { breakpoints: { sm: 576, md: 768, lg: ...

Unlocking secure content with Ajax

Trying to access a webservice or webpage solely through ajax, as it is the only allowed method for some reason. The webservice is secured with corporate SSO. When requesting webpage X for the first time, you are redirected to login page Y, outside of the a ...