How can I make sure that another function will only be executed after the completion of a function in

I'm currently working on an app with Angular CLI, and I am trying to retrieve a list after an insertion. Despite trying various methods such as observer, promise, async, setTimeout, etc., I haven't been able to find the right solution yet. I feel like I might be close, but something is missing.

Below is the code I have so far. In the insertStatut() function, I perform the insertion (service.insertStatuts()) and then immediately call getStatuts() to update the list.

Here is the code in my component :

import { Component, OnInit } from '@angular/core';
import { MatStatutService } from '../mat-statut.service';
import { MatStatut } from '../matStatut';

@Component({
  selector: 'app-mat-statut',
  templateUrl: './mat-statut.component.html',
  styleUrls: ['./mat-statut.component.css']
})
export class MatStatutComponent implements OnInit {
  private statuts: MatStatut[];
  private inStatut = new MatStatut;

  constructor(private service:MatStatutService) {
  }

  // get statuts at launch
  ngOnInit() {
    this.getStatuts();
  }

  // get list of statuts
  public getStatuts(): void{
    this.service.getStatuts().subscribe(posts => this.statuts = posts);
    console.log(this.statuts);
  }

  // insert a new statut
  public insertStatut():void{
    this.inStatut.setLibelle('Test');
    // insert new statut
    this.service.insertStatut(this.inStatut);
    // refresh list of statuts
    this.getStatuts();
    // reset insertion Statut
    this.resetMatStatut(this.inStatut);
  }

  // reset statut
  public resetMatStatut(statut: MatStatut){
    statut.resetData();
  }
}

And here is the code in my service:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { MatStatut } from './matStatut';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class MatStatutService {
  constructor(private http: HttpClient) {}

  getStatuts(): Observable<MatStatut[]>{
    return this.http.get<MatStatut[]>('http://localhost/rest/fonctions/matStatut/getAll.php');
  }

  insertStatut(statut: MatStatut) {
    this.http.post('http://localhost/rest/fonctions/matStatut/create.php', {
      mat_statut_libelle: statut.getLibelle()})
      .subscribe(
        res => {
          console.log(res);
        },
        err =>{
          console.log(err);
        });
  }
}

I hope my explanations are clear enough, and please forgive any mistakes in my English.

Answer №1

It seems like the issue lies within the inserStatus function of MatStatutService. You can make a simple change to fix it:

insertStatut(statut: MatStatut) {
 return this.http.post('http://localhost/rest/fonctions/matStatut/create.php', {
  mat_statut_libelle: statut.getLibelle()});
}

In your component, make sure you have the following code:

public insertStatut():void{
 this.inStatut.setLibelle('Test');
 // insert new statut
 this.service.insertStatut(this.inStatut).subscribe(res => {
    console.log(res);
    // refresh list of statuts
    this.getStatuts();
    // reset insertion Statut
    this.resetMatStatut(this.inStatut);
 }

By following this approach, you can ensure that the insertion happens first before retrieving the updated list.

P.S. It's worth mentioning that we are using Angular and not Angularjs in this context.

Answer №2

Stephane, it seems there are a few areas where improvements can be made

1.-When creating a Service, it is recommended to have it return Observables. To verify if everything went well, you can utilize "pipe(tap)" for Rxjx 6.0 or "do" for Rjxs 5.0

insertStatut(statut: MatStatut) {
    //simply return httpPost
    return this.http.post('http://localhost/rest/fonctions/matStatut/create.php', {
      mat_statut_libelle: statut.getLibelle()}) //Using pipe.tap to display the result
      .pipe(tap(res=>{console.log(res)}))
  }

2.-Within your component, ensure that when you call insertStatus and subscribe to the Observable, your code resides INSIDE the "subscribe". Any operations outside of subscribe won't have access to the value.

public insertStatut():void{
    this.inStatut.setLibelle('Test');
    // inserting new statut
    this.service.insertStatut(this.inStatut).subscribe(res=>
      { //Here you can handle the response
        //You can perform actions based on the response
        //But remember, all actions should be INSIDE subscribe
       this.getStatuts();
       this.resetMatStatut(this.inStatut);
      };
    // the lines below are not executed as they are OUTSIDE
    //this.getStatuts();
    //this.resetMatStatut(this.inStatut);
  }

Kindly ensure that your function getStatus() looks like this

  public getStatuts(): void{
    this.service.getStatuts().subscribe(posts => 
     { //Once again, console.log should be placed INSIDE
       this.statuts = posts;
       console.log(this.statuts);
     })
  }

NOTE: I acknowledge that my advice aligns with what Luax mentioned before :(

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

updating rows in a table

Currently, I have a grid array filled with default data retrieved from the database. This data is then displayed on the front end in a table/grid format allowing users to add and delete rows. When a row is added, I only want to insert an empty object. The ...

Encountering an issue with the Angular router-outlet: Unable to find any matching routes for the specified

I must apologize as I have searched extensively for a solution to my problem, but unfortunately, I have not been successful despite numerous attempts. Currently, I am working with Angular version 13.3.9 I am attempting to utilize the outlet router functi ...

Adding a Third-Party JavaScript Plugin to Angular 7

I've been attempting to integrate the read-excel-file JavaScript plugin into my Angular 7 project. Despite following all the methods recommended on various websites, I have yet to succeed. Could anyone provide a better solution? declare var readXlsx ...

What is the best way to recycle a single modal in Ionic?

Apologies for the vague title, but I'm facing an issue with creating a single modal to display data from multiple clickable elements, rather than having separate modals for each element. For example, when I click on item 1, its data should be shown in ...

Update header component dynamically upon successful login with Angular 11

I am currently using Angular 11 and facing an issue with displaying the username in the header component. The header loads before the login component, which results in the user data being stored in local storage only after the login component is loaded. As ...

Having trouble with nativescript-pager after updating nativescript-cli to version 6.0?

Error Found:- ERROR TypeError: Could not load view for: Pager.TypeError: Unable to access property 'PagerAdapter' of null ERROR TypeError: TNSViewPager is not a constructor Sample Code Snippet:- <Pager row="0" [items]="itemList" [selecte ...

Obtain the specific generic type that is employed to broaden the scope of a

I am working on a class that involves generics: abstract class Base<P extends SomeType = SomeType> { // ... } In addition, there is a subclass that inherits from it: class A extends Base<SomeTypeA> { // ... } I'm trying to figure out ...

What is the best way to include the number 7 and other lower numbers in an array?

I am facing an issue where I need to retrieve all the months that have passed in 2020, such as January, February, March, April, May, June, July, and August, and store them in an array. After executing the code below, my variable 'month' returns ...

Modal for Firestore CRUD operations update()

Currently seeking assistance with a CRUD system that involves modal dialogues. I have successfully implemented adding and deleting functionalities, but I am encountering an issue with editing. Although I can retrieve the data for each record in its respect ...

Using Typescript and webpack to detect variables that are defined in the browser but not in Node environment

My goal is to create a package that can be used on both servers and clients with minimal modifications required. Some libraries are available in Node but not in a browser, while others are accessible in a browser but not in Node. For instance, when utili ...

Encountered a higher number of hooks rendered compared to the previous render error on a component without any conditional hook usage

Within my codebase, I have a component that is responsible for rendering a clickable link to initiate a file upload process. import { gql, useLazyQuery, useMutation } from '@apollo/client'; import { useEffect, useState } from 'react'; i ...

Angular relative routes are failing to function

I am currently working on implementing a feature module in my project and following the documentation provided. My crisis-routing.module file looks like this: import { NgModule } from '@angular/core'; import { Routes, RouterModule } from ' ...

Using local variables in Angular2 templates

For the specific scenario discussed below, I have assigned the local variable #input to multiple radio buttons. My goal is to select the radio button within the <tr> when it is clicked. Surprisingly, the provided code functions as expected, yet the ...

Find a string that matches an element in a list

I currently have a list structured like this let array = [ { url: 'url1'}, { url: 'url2/test', children: [{url: 'url2/test/test'}, {url: 'url2/test2/test'}], { url: 'url3', children: [{url: & ...

Tips for improving the slow compilation of the Next.js 14 development environment

Currently, I am tackling an issue with my Typescript - Next.js 14 Application where the compilation process in the development environment is taking excessive time, sometimes up to 60 seconds. What steps can be taken to resolve this problem and optimize t ...

Establishing an efficient development environment with continuous integration for react-native using typescript and nodejs

Unfortunately, we encounter the challenge of working with different nodejs versions in our projects. I am unsure if this is similar to Java where multiple jdks can be installed (multiple nodejs installations), and each project automatically utilizes the co ...

What could be causing issues with my unit tests in relation to Angular Material tooltips?

I have a unique and specific issue with the following unit test code. It is very similar to another working file, but I am encountering an error related to mdTooltip from the Angular Material library. Here's the problematic portion of the code: Phant ...

Dealing with Angular 2's Http Map and Subscribe Problem

Looking to parse a JSON file and create a settingsProvider. This is how I am attempting it: import {Http} from "angular2/http"; import {Injectable} from "angular2/core"; @Injectable() export class SettingsProvider{ url: string = ""; constructor ...

finding the parent of form controls in Angular 2 requires understanding the hierarchical structure

Is there a way to access the parent form group of a nested form group in order to retrieve a sibling control value during validation? Both controls are within a formGroup that is part of a formArray. While I am aware of the root element, I am unsure how ...

Tips for Modifying the currentUrl identifier in Angular 2

I am trying to change the ID property of my currentUrl object within my component. My goal is for the ID to update and then fetch the corresponding data based on that ID. However, I keep encountering this error message: "Cannot assign to read only propert ...