Ways to refresh the information displayed on the view when the observable data is updated

I am using an observable called getContentfulEntry to retrieve data, while also passing data from another observable known as stateService.

this.langSubscription = this.stateService.getLanguage()
      .subscribe(val => {
        this.lang = val;
      });
      
    this.subscription = this.contentfulService.getContentfulEntry(this.footerEntryId, {locale: this.lang.toLowerCase()})
      .subscribe(res => {
        console.log('Footer Entries:: ', res);
        // this.contentfulData = res;
        this.filteredFooter = this.contentfulService.getFilteredEntryByProv(res, this.prov);
        console.log('Filtered Footer:: ', this.filteredFooter);
      });

Additionally, I am passing it as a parameter so that new data is fetched whenever this.lang is updated. However, the data in the view does not update automatically with this.subscription; manual refresh is required. Any suggestions on how to address this issue?

Answer №1

It appears that you are accessing the data returned from stateService.getLanguage() before it has returned a value.

To ensure that this.lang has a value, make sure to call getContentfulEntry() within the subscription to getLanguage(). This way, this.lang will have a value when getContentfulEntry() is called.

this.langSubscription = this.stateService.getLanguage()
  .subscribe(val => {
    this.lang = val;
    this.subscription = this.contentfulService.getContentfulEntry(this.footerEntryId, { locale: this.lang.toLowerCase() })
      .subscribe(res => {
        console.log('Footer Entries:: ', res);
        this.filteredFooter = this.contentfulService.getFilteredEntryByProv(res, this.prov);
        console.log('Filtered Footer:: ', this.filteredFooter);
      });
  });

Another approach is to assign the value returned from getLanguage() to a BehaviorSubject from rxjs. This allows you to subscribe to the BehaviorSubject, which emits a value every time a new value is assigned. While using behavior subjects can help manage changing parameters over time, it may not be the best practice for this scenario.

lang = new BehaviorSubject<string>('');

this.langSubscription = this.stateService.getLanguage()
  .subscribe(val => {
    this.lang.next(val);
  });

this.lang.subscribe(val => {
  this.subscription = this.contentfulService.getContentfulEntry(this.footerEntryId, { locale: this.lang.getValue().toLowerCase() })
    .subscribe(res => {
      console.log('Footer Entries:: ', res);
      this.filteredFooter = this.contentfulService.getFilteredEntryByProv(res, this.prov);
      console.log('Filtered Footer:: ', this.filteredFooter);
    });
});

Answer №2

Because API calls in Angular are asynchronous, the request to getContentFulEntry() is being made before the completion of the getLanguage() call. This results in the fulentry call using the same outdated language, causing the UI not to reflect the updated language. To address this issue, ensure that the second method is only called after the first one has completed successfully.

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

Ensuring type compatibility in a declarative manner: What are the methods?

My goal is to establish a compile-time constraint that ensures a variable of type T2 can be assigned to a variable of type T1. If I have a value (t2) of type T2, I can simply do the following: const t1: T1 = t2; Is there an alternative method to achiev ...

What other intentions am I forgetting?

Encountering an error regarding missing intents but unable to determine which intents are missing. Various attempts have been made to rectify the issue without success. What specific element is absent here? The following code snippet represents only a po ...

Trouble displaying custom markers in VueJS using Google Maps API

I have integrated vue2-google-maps to display a map and add markers on specific locations. Here is the code snippet showing the map components along with the props passed to it. <gmap-map id="map" :center="center" :zoom="5" ...

Refreshing Slickgrid: Updating grid data with data fetched from an AJAX source

Within the app I am developing, there exists a data grid alongside select boxes that allow users to set filters. Upon selection of these filters, an AJAX call is made to retrieve a new array of data from the server. The challenge I currently face is wipin ...

Tips for removing ASP.NET MVC controller name from angular route

My ASP.NET MVC login page leads to a different page that is integrated with Angular. After logging in, the URL looks something like this: http://localhost:5083/Home#/home I want to remove the ASP MVC controller name ("Home") from the URL. Is there a ...

Having a hard time implementing a subtracting callback function in a JavaScript reduce function

Currently, I am tackling a code challenge in JavaScript that requires me to develop a function called reduce. This function is responsible for reducing a collection to a value by applying a specific operation on each item in the collection over which it it ...

Having trouble with Angular 2 not refreshing the view after a database record update

I am working on a CRUD application using Angular 2. The homepage shows a list of cards that users can create, edit, or delete. When I edit a card and click submit on the edit page, it triggers the following function: card-edit.component.ts onSubmit() { ...

Learn how to display a tooltip for every individual point on a Highcharts network graph within an Angular

I am currently working on developing network graphs using highcharts and highcharts-angular within my Angular application. I have successfully managed to display the graph with datalabels, but now I need to implement tooltips for each point or node on the ...

Exploring the world of WebSockets and Socket.io

Recently many online games, like , have started using WebSockets to create real-time MMORPGs. I'm curious about how to develop a node.js program that can manage connections from browsers using WebSockets. Here is an example of browser code: <!DOC ...

Tips for disabling the default behavior by using preventDefault in JavaScript

I need help with removing the preventDefault() function and submitting the form in the else condition of my code. Does anyone know how to achieve this? if(email.val() != ""){ //check email e.preventDefault(); $.ajax({ ...

Transfer the data-url attribute to the jQuery ajax URL

I am facing an issue with my form which includes a data-attribute holding a URL to an API JSON file: <form class="product" action="#" data-url="dist/scripts/main.js"> [...] </form> My goal is to transfer the URL from the data attribute to ...

Evaluating different attributes within a single entity

I was attempting to write some code that checks if two individuals share the same birthday. Person "a" and person "b" do not have the same birthday, yet the console output shows: a was born on day 1 a has the same birthday as a a has the same birthday as ...

Looking to ensure my HTML page is optimized for mobile devices

Struggling to create a responsive layout? I've added the meta viewport tag, but still can't get it right. Maybe we can try zooming out based on screen dimensions to prevent the use of a horizontal scrollbar. <html> <head> <meta n ...

Concealing Contact Form Using Javascript

Upon making adjustments to a website, I encountered an issue with the contact form. The form is meant to be hidden on page load and only appear when the envelope icon is clicked. However, currently the form is visible by default, and clicking the envelope ...

Issue with Figma React plugin's PostMessage functionality not behaving as anticipated

I am currently working on developing a plugin for Figma, following the react example provided on their GitHub page: https://github.com/figma/plugin-samples/tree/master/react One of the functionalities I have implemented is a button that triggers a specifi ...

Toggle visibility of multiple DIVs with identical classes using radio buttons

I'm looking to streamline my use of radio buttons in HTML. How can I implement a single set of radio buttons at the top that will toggle the visibility of all DIVs with the same class on my webpage? <form> <input type="radio" name="csr_sel ...

Tips for modifying the class of a span inline element using a javascript function

Looking for assistance in creating a password text box with an eye icon that toggles visibility. When the user clicks on the eye icon, it should change to a crossed-out eye icon and switch the input type to text. <div class="input-group show-hide-passw ...

Top method for verifying input during keyup or blur events

When it comes to validating user inputs, I often find myself wondering about the best approach to take. In this case, I have created a regex for numbers with decimal points. .ts part checkIsNumber(event) { console.log('event', event.target. ...

Content that is displayed by default for ng-content when utilizing ngIf

I have created an Angular 9 component called inner: <div #ref> <ng-content select="[content]"></ng-content> </div> <ng-container *ngIf="!ref.hasChildNodes()"> <div>Default value</div> &l ...

Turn off hover effect for the v-checkbox component in Vuetify 2

Is there a way to prevent the darkened circle from appearing behind a v-checkbox in Vuetify 2 when hovering over it? My v-checkbox is currently enclosed within a v-tab and a v-tooltip, although I'm not sure if that has any impact. <v-tab v-for=&quo ...