How can I postpone the initialization of ngOnInit in Angular 7?

While attempting to send and retrieve data for display, I encountered an issue where the component initializes before the new data is added to the server. This results in a missing element being displayed.
Is there a way to delay the initialization process, allowing for the post request to be made first, followed by the get request to ensure all elements are properly displayed?

create-organisme.component.ts:

import { Component, OnInit } from '@angular/core';
import { OrganismeService } from '../organisme.service';
import { Organisme } from '../organisme';
import { Router } from '@angular/router';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-create-organisme',
  templateUrl: './create-organisme.component.html',
  styleUrls: ['./create-organisme.component.css'],
  providers: [OrganismeService]
})
export class CreateOrganismeComponent implements OnInit {
  organisme: string;
  description: string;

  form = new FormGroup ({
    nom: new FormControl(''),
    description: new FormControl(''),
  });

  constructor(private orgService: OrganismeService, private router: Router) { }

  ngOnInit() {
  }

  create(): void {
    const org = new Organisme();
    org.organisme = this.form.get('nom').value;
    org.description = this.form.get('description').value;
    this.orgService.create(org)
    .subscribe(
      (error) => {
        console.log('Erreur: ' + error);
      }
    );
    this.router.navigate(['/display']);
  }
}

display-organisme.component.ts:

import { Component, OnInit } from '@angular/core';
import { Organisme } from '../organisme';
import { OrganismeService } from '../organisme.service';

@Component({
  selector: 'app-display-organisme',
  templateUrl: './display-organisme.component.html',
  styleUrls: ['./display-organisme.component.css'],
  providers: [OrganismeService]
})
export class DisplayOrganismeComponent implements OnInit {

  organismes: Organisme[];
  selectedOrganisme: Organisme;

  constructor(private orgService: OrganismeService) { }

  onSelect(organisme: Organisme): void {
    this.selectedOrganisme = organisme;
  }

  ngOnInit() {
    this.orgService.getOrganismes().subscribe(orgs => this.organismes = orgs);
  }

}

Is it advisable to move the router navigation within the subscribe method so that it waits for the response before redirecting?

Answer №1

There is no need to postpone the execution of ngOnInit(). Just make a simple adjustment by relocating the line below:

this.router.navigate(['/display']);

Place it inside the subscribe() function as shown below:

this.orgService.create(org)
    .subscribe(
      (result) => this.router.navigate(['/display']),
      (error) => {
        console.log('Error occurred: ' + error);
      }
    );

Answer №2

To add a delay to your get request, you can utilize the debounce() function along with a specified timer. Here is an example implementation:

return this.http.get(some_url) 
   .pipe(
      debounce(() => timer(1500)), // 1.5 seconds
      catchError(this.handleError)
   );

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 type '{}' does not contain a property named 'map'

Recently delving into TypeScript, and I'm curious about the process of typing an axios response when storing it in a state variable. I've initiated a basic API call from App.tsx, which returns the following object: {data: {…}, status: 200, s ...

typescript persist zustand: typing your store

Running a simple store interface CartState { cart: { [id: string]: CartDto }; addItem: ({ id, image, name, price }: Omit<CartDto, "quantity">) => void; removeItem: (id: string) => void; reset: () => void; } export const use ...

Angular CLI's selection of third-party libraries that are not available on npm repositories

Currently in the process of migrating an app from Angular 2 to Angular CLI Now facing the challenge of importing 3rd party libraries like orbitcontrols.js that are not available on npm or bower. After researching on https://github.com/angular/angular-cli ...

What is the best approach to integrate react-hooks, redux, and typescript seamlessly?

Struggling to seamlessly integrate React-hooks, Redux, and Typescript. It's a never-ending cycle of fixing one error only for another to pop up. Can anyone pinpoint what the root issue might be? Currently facing the following error related to my red ...

Utilize an enum to serve as a blueprint for generating a fresh object?

I've defined an enum as shown below: export enum TableViewTypes { user = 'users', pitching = 'pitching', milestones = 'milestones', mediaList = 'mediaList', contacts = 'contacts' } ...

Is it possible to integrate the Firestore npm library into my Express application?

Recently, I created my own library to act as a nosql database on my node.js web server in place of mongodb. I came across this interesting quote: Applications that use Google's Server SDKs should not be used in end-user environments, such as on pho ...

What is the best way to set a boolean value for a checkbox in a React project with Typescript?

Currently, I am working on a project involving a to-do list and I am facing an issue with assigning a boolean value to my checkbox. After array mapping my to-dos, the checkbox object displays 'on' when it is unchecked and a 'Synthetic Base E ...

Steps for Adding a JSON Array into an Object in Angular

Here is a JSON Array that I have: 0: {name: "Jan", value: 12} 1: {name: "Mar", value: 14} 2: {name: "Feb", value: 11} 3: {name: "Apr", value: 10} 4: {name: "May", value: 14} 5: {name: "Jun", value ...

How can I bind Angular to the selection of a file input field?

I am facing an issue with my upload form where the displayed filename is showing a virtual filepath instead of just the filename itself. How can I improve the binding to only display the filename (like selected.files[0].name) without any virtual path? My ...

Angular array of considerable size

Dealing with a massive array of 30,000 items can be quite daunting, especially when it comes in as a stream using grpc-web. Currently, I'm fetching the data from grpc.client() and populating an array before displaying it using *ngFor. However, I' ...

Does Angular 8 development mode implement tree-shaking?

I am curious to know if tree-shaking occurs during Angular 8 development mode. When running the following command: ng build I understand that tree-shaking happens when I use the command below: ng build --optimization=true|false ...

Transferring image data from Angular to ExpressJS using blobs

While attempting to send a blob image, I encountered an Error: Unexpected end of form when using multer with Serverless Framework. Upon checking console.log https://i.sstatic.net/s8VSs.png My understanding is that I need to append it to FormData before s ...

Ensure that only numbers with a maximum of two decimal places are accepted in Angular 2 for input

On my webpage, there are several input boxes where users can enter numbers. I need to prevent them from entering more than two decimal places. Although I tried using the html 5 input Step="0.00", it didn't work as expected. I am open to any TypeScri ...

What type of event does the Input element in material-ui v1 listen for?

I'm currently grappling with material-ui v1 as I search for the appropriate event type for input elements. Take a look at the code snippet below: <Select value={this.numberOfTickets} onChange={this.setNumberOfTickets}> .... Here is the impleme ...

Leverage ngFor to loop through a "highly intricate" data structure

In my project, I have stored data in a JSON file structured as follows: { "name": { "source1": ____, "source2": ____, "source3": ____ }, "xcoord": { "source1": ____, "source2": ____, "source3": _ ...

Tips on ending an interval in rxjs once it has started

Implemented a code in an Angular component to retrieve data from a service every 10 seconds on initialization. Now, I need to find a way to stop the interval after a certain period of time such as 5 minutes or when all the necessary data has been collected ...

Enhancing the appearance of the Mui v5 AppBar with personalized styles

I am encountering an issue when trying to apply custom styles to the Mui v5 AppBar component in Typescript. import { alpha } from '@mui/material/styles'; export function bgBlur(props: { color: any; blur?: any; opacity?: any; imgUrl?: any; }) { ...

What caused the mat-date calendar style to malfunction?

I integrated mat-date into my Angular project, but encountered an issue where the styles of the calendar were not displaying properly when clicking the icon. Here is the displayed calendar effect I attempted to troubleshoot by commenting out the styles o ...

An easy guide on incorporating external npm modules into Angular 2, such as an encryption library

Within my Angular 2 application (utilizing the SystemJS module manager and Typescript as the scripting language), I am in need of importing an npm module for encryption purposes. This could be either Crypto-JS, Forge-JS, or any alternative that serves the ...

Navigate to a specific line in Vscode once a new document is opened

Currently, I am working on a project to create a VS Code extension that will allow me to navigate to a specific file:num. However, I have encountered a roadblock when it comes to moving the cursor to a particular line after opening the file. I could use so ...