When implementing ReplaySubject in Angular for a PUT request, the issue of data loss arises

I seem to be encountering a problem with the ReplaySubject. I can't quite pinpoint what I've done wrong, but the issue is that whenever I make a change and save it in the backend, the ReplaySubject fetches new data but fails to display it on the screen. I attempted using detectChanges without success. I understand that detectChanges only functions within a parent-child relationship.

This issue occurs during updates https://i.sstatic.net/DHfRC.png

And this happens upon reloading the page https://i.sstatic.net/GoX0H.png

If I eliminate this.data.next(res) from this line of the Put Request, everything works. However, I have to refresh the page to see the updated data again.

 return this.http.put(api, dataModel).subscribe(res => this.data.next(res));

Here's the code snippet for the service.

@Injectable({
  providedIn: "root"
})
export class ModelDataService {
  public baseUrl = environment.backend;
  private data = new ReplaySubject<any>();
  public userID = this.authService.userID;


  constructor(private http: HttpClient, private authService: AuthService) {
  }

   public getJSON() {
    return this.http.get(`${this.baseUrl}/data/${this.userID}`).subscribe(res => this.data.next(res));
  }

  public dataModel(): Observable<any> {
    return this.data.asObservable();
  }
  public setData(data: Model) {
    const api = `${this.baseUrl}/data`;
    const user_id = this.authService.userID;
    this.http.post(api, data, {
      headers: {user_id}
    }).subscribe(res => this.data.next(res));
  }

  public updateDate(id: string, dataModel: Model) {
    const api = `${this.baseUrl}/data/${id}`;
    return this.http.put(api, dataModel).subscribe(res => this.data.next(res));
  }
}

Now moving onto the component.

 public model$: Observable<Model>;
 public model: Model;


 constructor(
    public authService: AuthService,
    private modelDataService: ModelDataService,
    public dialog: MatDialog,
    public cd: ChangeDetectorRef) {
  }
  ngOnInit() {
    this.authService.getUserProfile(this.userID).subscribe((res) => {
      this.currentUser = res.msg;
    });
    this.modelDataService.getJSON();
    this.model$ = this.modelDataService.dataModel();
    this.model$.subscribe((data) => {
      this.model = data; // here if i try to console log then I have the array but the page it will be blank
    console.log(data);
    });
  }

As an example, I attempt to display data like so.

   <ng-container class="Unit-unit-unitGroup" *ngFor="let personalData of model.personalData; let id = index">
</ng-container>

In the put Request, when I added a console log, this is what I observed. https://i.sstatic.net/vmfaG.png

However, upon reloading, it seems like the data structure changes. See imagehttps://i.sstatic.net/s2l2O.png

Answer №1

Employ ChangeDetectorRef to identify changes in the view after receiving new data.

this.updatedModel$.subscribe((updatedData) => {
  this.updatedModel = updatedData;
  this.changeDetectorRef.detectChanges();
});

Answer №2

<ng-container class="Unit-unit-unitGroup" *ngFor="let personalData of model.personalData; let id = index">
</ng-container>

this.model$.subscribe((data) => {
      this.model = data; // after attempting to console log, the array is visible but the page remains blank
    console.log(data);
    });

public updateDate(id: string, dataModel: Model) {
    const api = `${this.baseUrl}/data/${id}`;
    return this.http.put(api, dataModel).subscribe(res => this.data.next(res));
  }

You anticipate personalData to be a property of your model. However, as shown in the console log, your res is an object with data nested within it. To rectify this, you simply need to map res to its data property.

public updateDate(id: string, dataModel: Model) {
    const api = `${this.baseUrl}/data/${id}`;
    return this.http.put(api, dataModel).subscribe(res => this.data.next(res.data));
  }

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

Guide on setting a JSON object using the getJSON method

In my coding project, I am trying to assign values of lat and lng from a JSON object named branch to a variable called jsonData. When I use console.log to check jsonData.responseJSON.positions.length or jsonData.responseJSON.positions[0].lat, etc. I c ...

Send PHP data through AJAX and retrieve it on a different PHP page

I need to send a variable through an AJAX URL to another PHP page and retrieve it using: $id=$_GET['id']; Here's an example where the value is passed, for instance $id=6. <a id="pageid" href="ifsc-bank.php?id=<?=$id?>"><im ...

Efficiently loading Angular Material components in feature modules

Currently, my Angular module named MyAngularModule looks like this: /app/material/material.module.ts import { MatButtonModule, MatIconModule } from '@angular/material'; const MaterialComponents = [ MatButtonModule, MatIconModule, ... ]; @ ...

Navigating with Node.js: Understanding how to showcase the response data within a list structure

I am brand new to working with node.js and I'm looking to display the data I receive as a response on my webpage. Currently, I can see the output in my console. Is there a way to show this data on my actual page? GET Request: app.get('/bestell_ ...

Is JavaScript still running despite not displaying insecure items due to IE 8 security warning?

After a user completes a transaction on my site, the confirmation page displays Google conversion tracking code in a small JavaScript snippet. This code is located on my Wordpay callback page, which pulls data from the regular site (HTTP) to the Worldpay s ...

Pass an array containing an HTML string to the $.post method in jQuery

I have a problem with displaying HTML content fetched from a PHP script using the jQuery $.post method: $.post('{$site_url}tests/tests/content', params, function (data) { $('#some-div1').html(data[1]); $('#some-div2').htm ...

What are some solutions for troubleshooting a rapid-moving Selenium web driver?

My code is not functioning correctly and I need a better solution. The fast speed of execution makes it difficult for me to detect where the issue lies. Below is my current code: public static void main(String[] args) { //**************************** ...

Ways to Determine the Height and Width of an Image Once it has been Adjusted for a View

Is there a way to retrieve the height and width of an image after it has been resized for a view? I have images that may vary in original dimensions, but users can resize them as needed. For example, this code from the console gives the client height: do ...

Combine the values of two text fields from separate input fields to populate a new text field across several lines

https://i.sstatic.net/fp8aZ.png I am seeking a way to automatically calculate the total cost by multiplying the quantity and unit cost values for each line entered. Despite my attempts with the jQuery script provided below, I have been unable to achieve t ...

Angular design pattern: organizing rows according to the month

I currently possess the following items: { "pk": 33, "name": "EVENT 634", "start_date": "2022-05-11T00:00:00", "end_date": "2022-05-14T00:00:00" }, { "pk": ...

``Troubleshooting Problem with Tailwind's Flex Box Responsive Grid and Card Elements

Starting point: Preview https://i.sstatic.net/zfzBU.jpg Code : <div class="container my-12 mx-auto"> <div className="flex flex-wrap "> {error ? <p>{error.message}</p> : null} {!isLoading ...

The function '$("#elementId").change()' is not functioning correctly, while '$(document).on("change" "elementId")' is operating effectively

Recently, I have encountered an issue on my web pages where the $("#elementId").change() function does not work for elements on a JSP page. However, using $(document).on("change" "elementId") seems to work. It appears that the page's document is being ...

Issue with Passport Google Oauth login redirection to successful route

I am currently following a tutorial on setting up Google Oauth in my Express app using Passport.js. The tutorial can be found here. Below are the routes defined in my server.js file: // Code snippet here The server.js file also imports configurations fro ...

Slideshow elements removed

I attempted to remove my links individually from the div id="wrapper", but unfortunately have encountered an issue while doing so: window.onload = function () { setInterval(function () { var wrapper = document.getElementById("wrapper"); var my_l ...

Exclude specific outcomes within a nested document in MongoDB

I have a situation where I need to query a list of items and only retrieve the ones that correspond to a specific ID in the provider_cost_dict. Essentially, if I input providerId = 10001, then only the items with a matching entry in the provider_cost_dict ...

Is there a way to identify if the parent page has completed loading while within an iframe?

Is there a way to detect properties or events within the iframe that can help determine this? The src of the iframe and the parent page belong to different domains. ...

utilizing regular expressions to retrieve data

I am facing a challenge in extracting both the product name and price from the given data. The desired result, which includes both the product name and price, is not on the same line. How can I include the line that comes before the price as well? Here is ...

The json_encode() function returned a JSON that is not valid

In my PHP file (although more complex, even with the simplest code it fails), I have: <?php $salida = array(1,2,3,4,5); echo json_encode($salida); ?> The response received is: [1,2,3,4,5] While this appears valid, it's actually not. When pas ...

Navigation through Image Filters

Everything seems fine with my code, but when I click on the navigation links, they direct me to index.html or the landing project instead of filtering the images. How can I modify the links to properly filter the images? This is the Javascript and html co ...

The combination of using the .share() method with the .subscribe() method is resulting in

I encountered an issue while attempting to utilize share() with subscribe(). Despite starting with subscribe, I received the following error message. How can this be resolved? The main goal is to execute the logic within subscribe. Share is necessary to p ...