1

Hi I have a code where everything works as expected, for a page where i can update some fields(Day of week, open time and closing time). I can update it successfully by clicking the update button (in the logs the data is sent to server side as well) and it navigates to the table for the updated data, but sometimes i have to refresh the page again to see the updated values. This also happens sometimes on other tabs for example when adding new data to the table. I don't know if it is caused by Angular or the server side(spring-boot) or something else. Thanks in advance.

Here's my code:

import { Component, OnInit, Inject } from '@angular/core';
import { Router } from "@angular/router";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { first } from "rxjs/operators";
import { RegularDaysService, RegularDays } from '../service/regular-days.service'
@Component({
  selector: 'app-edit-regulardays',
  templateUrl: './edit-regulardays.component.html',
  styleUrls: ['./edit-regulardays.component.css']
})
export class EditRegularDaysComponent implements OnInit {

  regDay: RegularDays;
  editForm: FormGroup;

 constructor(
    private router: Router,
    private httpClientService: RegularDaysService,
    private formBuilder: FormBuilder
  ) { }

  ngOnInit() {
    let regDayId = window.localStorage.getItem("editRegularDaysId");
    if (!regDayId) {
      alert("Invalid action.")
      this.router.navigate(['regulardays']);
      return;
    }
    this.editForm = this.formBuilder.group({
      id: [],
      dayOfWeek: [''],
      openFrom: ['', Validators.required],
      openTo: ['', Validators.required],
    });
    console.log(this.editForm.value);
    this.httpClientService.getRegularDaysById(+regDayId)
      .subscribe(data => {
        this.regDay = data;
        this.regDay.dayOfWeek = this.formatNumbersToDays(this.regDay.dayOfWeek);
        this.regDay.openFrom = this.formatTime(this.regDay.openFrom);
        this.regDay.openTo = this.formatTime(this.regDay.openTo);
        console.log(data);

        this.editForm.setValue(data);
      });
  }

// --some code for formatting data for database--

  onSubmit() {
    let formattedObject = this.formattedRegularDay(this.editForm.value);
    console.log(JSON.stringify(formattedObject));
    this.httpClientService.updateRegularDays(formattedObject)
      .pipe(first())
      .subscribe(
        data => {
          {
            // alert('Day updated successfully.');
            this.router.navigate(['regulardays']);
          }
        },
        error => {
          // alert(error);
        });
  }

}

my html:

<div class="col-md-6">
  <h2 class="text-center">Edit regular day</h2>
  <form [formGroup]="editForm" (ngSubmit)="onSubmit()">

    <div class="material-input">
      <mat-form-field class="form-group">
        <mat-label>Day of week</mat-label>
        <mat-select formControlName="dayOfWeek" placholder="Day of week">
          <mat-option *ngFor="let day of dayOfWeek" [value]="day">
            {{day}}
          </mat-option>
        </mat-select>
        <mat-error *ngIf="editForm.get('dayOfWeek').errors && (editForm.get('dayOfWeek').touched)">
          Please pick a day
        </mat-error>
      </mat-form-field>
    </div>

    <div class="material-input">
      <mat-form-field class="form-group" appearance="outline">
        <mat-label>Open from</mat-label>
        <input matInput readonly placeholder="Open from" formControlName="openFrom" [ngxTimepicker]="startTimePicker"
          [format]="24">
        <ngx-material-timepicker #startTimePicker></ngx-material-timepicker>
        <mat-error *ngIf="editForm.get('openFrom').errors && (editForm.get('openFrom').touched)">
          This field is required
        </mat-error>
      </mat-form-field>
    </div>

    <div class="material-input">
      <mat-form-field class="form-group" appearance="outline">
        <mat-label>Open to</mat-label>
        <input matInput readonly placeholder="Open to" formControlName="openTo" [ngxTimepicker]="startTimePicker2"
          [format]="24">
        <ngx-material-timepicker #startTimePicker2></ngx-material-timepicker>
        <mat-error *ngIf="editForm.get('openTo').errors && (editForm.get('openTo').touched)">
          This field is required
        </mat-error>
      </mat-form-field>
    </div>

    <button mat-raised-button color="primary" type="button" class="btn btn-success" [disabled]="!editForm.valid"
      (click)="onSubmit()" routerLink="/regulardays">Save</button>
  </form>
</div>

And my service:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from "rxjs/index";

export class RegularDays {
  constructor(
    public id: string,
    public dayOfWeek: string,
    public openFrom: string,
    public openTo: string,
  ) { }
}

@Injectable({
  providedIn: 'root'
})
export class RegularDaysService {

  constructor(
    private http: HttpClient
  ) { }

  baseUrl: string = 'http://localhost:8080/hm/rest/regulardays/';   //local

  getRegularDays() {

    const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
    return this.http.get<RegularDays[]>(this.baseUrl + '', { headers });
  }

  getRegularDaysById(id: number): Observable<RegularDays> {
    return this.http.get<RegularDays>(`${this.baseUrl}${id}`);
  }

  public updateRegularDays(regularDay: RegularDays): Observable<RegularDays> {
    const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
    return this.http.put<RegularDays>(`${this.baseUrl}${regularDay.id}`, regularDay, { headers });
  }
}

EDIT

If I add this: .then(() => { window.location.reload(); }); then it refresh but only on localhost, and not on server..

Kerk
  • 283
  • 1
  • 4
  • 24
  • Hi [Kerk](https://stackoverflow.com/users/10956322/kerk), could you please provide a [stackblitz](https://stackblitz.com/)? – Meziane Feb 10 '20 at 09:12

0 Answers0