The recently generated record will appear on the screen only when the page is refreshed

I have a modal window that contains a form to create new records. The desired functionality is as follows: when the user clicks on the create modal button, the window should close instantly, the newly created record should appear in the table, and a success message should be displayed indicating that the record was successfully created. However, currently only the modal window closure works correctly. To view the new record, the page needs to be manually refreshed, and the success message is not showing at all.

How can this issue be resolved?

import { Component, OnInit, Input, ViewContainerRef, TemplateRef } from '@angular/core';
import { DialogRef, ModalComponent } from 'angular2-modal';
import { Post } from '../../../../../models/post.model';
import { PostService} from '../../../../../services/post/post.service';
import { BSModalContext } from 'angular2-modal/plugins/bootstrap';
import { ToastsManager } from "ng2-toastr";
import { Angular2TokenService } from "angular2-token";
import { Observable } from 'rxjs/Rx';

@Component({
  selector: 'app-add-post',
  templateUrl: './add-post.component.html',
  styleUrls: ['./add-post.component.css'],
  providers: [PostService]
})

export class AddPostComponent implements OnInit, ModalComponent<any> {

  post = new Post;
  posts: Array<Post>;

  constructor(
    public dialog: DialogRef<any>,
    public authTokenService: Angular2TokenService, 
    private servPost: Post,
    public toastManager: ToastsManager,
    vcr: ViewContainerRef
  ) { 
    toastManager.setRootViewContainerRef(vcr);
  }

  ngOnInit() {
  }

  savePost() {
    this.servPost.createPost(this.post).subscribe
      (success => {
          this.toastManager.success('Data successfully created!', 'Done');
          this.servPost.getPosts().subscribe(posts => {
            console.log(posts);
            this.posts = posts;
          });
      }, error => {
        this.toastManager.error(getErrorTextFromJSON(error.json()), 'Error');
      });

      this.dialog.close(null); 
   }
}

Is there a way to automatically refresh the page after creating a new record? This would eliminate the need for manual page reloading to display the newly added record.

Answer №1

if the createPost function returns the newly created entity, you can follow these steps:

savePost() {
  this.servPost.createPost(this.post).subscribe(
     data => {

        this.toastManager.success('Data successfully created!', 'Done');

        // check the returned data from the REST service
        console.log(data);

        // add the returned data from the REST service to the posts array
        this.posts.push( data );

        this.dialog.close(null);

     }, 
     error => {
        this.toastManager.error(getErrorTextFromJSON(error.json()), 'Error');
     }
  );

}

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

The functionality of this.router.navigate in Angular 15 seems to be off, as it is throwing an error saying it is not

Just have a quick question: Check out this code snippet... import { DOCUMENT } from '@angular/common'; import { Component, HostListener, Inject, NgZone } from '@angular/core'; import { Router } from '@angular/router'; @Compo ...

New substitute for extending the extent in OpenLayers 4

I am currently in the process of migrating my code from OpenLayers 3 to OpenLayers 4 using TypeScript. Previously, I had a code snippet that extended the extent of my map so that all vector shapes I drew would be visible upon loading... angular.forEach(w ...

Ways to conceal scrollbar track

Is there a method to conceal the track of the scrollbar while keeping the thumb visible? The desired appearance is shown in the following image: https://i.sstatic.net/6TqmM.png However, the current view is as follows: https://i.sstatic.net/tdJq3.png Th ...

NestJS: Specify the data type for @Body()

Consider the code snippet below: @Post() public async createPet(@Body() petDetails: PostPetDto): Promise<any> { } In this scenario, the type of @Bod() petDetails defaults to plain/any instead of the declared type of PostPetDto. What is the recommen ...

Leveraging regular expressions for handling apostrophes

I need help with a function function convertToTitleCase(sentence: string) { return sentence.replace(/\b\w/s, word => word.toUpperCase()); } Current output: Men's apparel Desired output: Men's Apparel Can anyone assist me in achi ...

During the process of running mocha tests, an error is encountered stating that a "reflect-metadata shim is necessary when utilizing class decorators."

Recently, I wrote a Mocha test case using Chai in Typescript and followed the steps outlined in this article here to install all the necessary dependencies. However, when trying to run the test cases with "npm test", I encountered the following error mess ...

Error! Unexpected closure occurred while creating an Angular CLI project with npm

After cloning an Angular (4+) CLI project onto a new machine and running npm install, I encountered an error that reads as follows. This project works perfectly fine on other computers: npm ERR! premature close npm ERR! A complete log of this run can be ...

For Angular 9, remember to include a forward slash ("/") before the styles.css path in index.html following a production build

Is there a way to instruct Angular to always include a slash in front of the path for styles in the index.html during production builds? I need this to resolve an issue with a package that requires the slash. Currently, I'm manually adding it like thi ...

Ways to modify the appearance of the button within ion-calendar

Looking to customize the styling of ion-calendar classes Attempting to add styles to the ion-calendar-month class, but not seeing any changes take effect. ...

The issue of a memory leak occurring upon the destruction of the Observable source object

When you subscribe to an observable, what happens if the source of the observable is no longer used in the application? Is there a risk of memory leak? I have a FormArray containing multiple FormGroup elements. For each FormGroup, I am subscribing to its ...

Angular navigation did not work as expected

Created a basic webpage using Angular CLI version 8.3. The issue is as follows: For example: www.domainname.com is working fine. www.domainname.com/basicprinciples will work if visited through the main page, but it does not work when directly visiting w ...

Resolve the conflict with the upstream dependency in Angular

I understand that the solution to this issue can be found on SOF, but utilizing --legacy-peer-deps or --force is not an option for me on my production server. I am eager to comprehend the root cause of this error and find a proper resolution. Upon install ...

Is it still necessary to include /// reference path=" in TypeScript 2.0?

Do you still need to use /// reference path="" in TypeSctipt 2.0, like this: ///<reference path="../../../../typings/app.d.ts"/> or does TS now search all directories specified in tsconfig? I would appreciate a detailed answer... Thanks, Sean ...

Can you explain the reference to "ng2" in relation to Angular 2?

In countless blog posts discussing Angular 2, I often come across references to ng2. Can someone clarify what ng2 stands for? Is it the CLI for Angular 2? ...

Encountering a challenge with triggering a dialog box from an onClick event on a pie chart in Angular 8 when utilizing chart.js

I am currently using a chart.js pie chart to showcase some data. I have managed to display the required information in an alert box when a slice of the pie is clicked. However, I am now looking for a way to present this data in a dialog box instead. &a ...

Is it necessary to include the file name in the path when uploading a file to a network server from the intranet?

While using a REST tool to upload a file from the intranet to a network server, I encountered an error message: "Access to the path '\\\servername.com\subfolder1\subfolder2\file_name' is denied" I am wondering if t ...

Steps to stop mat-spinner upon receiving Job Success/Failure Notification from the backend

I have a task that runs asynchronously and takes a long time to complete. When the task starts, I display a mat-spinner with a timeout set at 60000 milliseconds. However, we now have a notification service that provides updates on the job status. I would l ...

What is the best way to incorporate an array of strings as a value while updating a state object?

I have written some code with the intention of concatenating two strings later on. However, I am struggling to update the state properly using a handleChange function. The error message I'm receiving states that "A spread argument must either have a t ...

Unexpected results can occur when using ngClass and CSS with all unset

Within my Angular 4 project, I am utilizing ngClass on an object that contains a CSS class applied with unset: all within it. Despite knowing that ngClass adds its properties, the expected result was for all values to be unset and the style elements from n ...

Using a factory function within a Typescript declaration file, both with and without the utilization of the new keyword

Here is an example of a factory function created in ES5: function MyClass(val) { if (!(this instanceof MyClass)) { return new MyClass(val); } this.val = val; } You can call this function with or without the new keyword: var a = new ...