0

I'm building an application that post an object_1 in a table then collect the ID inserted in the json response. After that, I want to post another object_2 that use also the ID inserted of my first object but the problem is that the insertedID is always undefined

//******** The interface **********
export interface PostResult__ {
fieldCount: number;
affectedRows: number;
insertId: number;
serverStatus: number;
warningCount: number;
message: string;
protocol41 : boolean;
changedRow :number;
}



//***** The service : ***********
export class AdressePostaleService {

constructor(private http: HttpClient) {}

addAdressePostale(adressepostale: AdressePostale): Observable<PostResult__>     
{
return this.http.post<PostResult__>    
(environment.apiUrl+'/api/adressespostale', adressepostale).pipe( 
catchError(this.handleError)
);
}
}

********* The component / The function that post the object ***************

PostID : PostResult__[]=[];
//Function Ajouter Agence dans la BDD

AjouterAdresse(){
    //Créer l'adresse postale
this._AdressePostale.Numero=this.firstFormGroup.value.Num_adresse;
this._AdressePostale.Voie=this.firstFormGroup.value.Voie_adresse;
this._AdressePostale.ID_Ville = this.VilleSelec.ID_Ville;

this.adresseservice.addAdressePostale(this._AdressePostale).subscribe(
adresse__=> this.PostID.push(adresse__));

console.log(this.PostID[0]);
}

Actual Results : console.log(this.PostID[0]); = Undefined

Excpetced Result : console.log(this.PostID[0]); = the json file with the last insertID

SoufH
  • 1
  • 2

1 Answers1

0

Subscribe is asynchronous. Console.log is running before the subscribe has finished, move console.log inside the subscribe block.

AjouterAdresse(){
    //Créer l'adresse postale
this._AdressePostale.Numero=this.firstFormGroup.value.Num_adresse;
this._AdressePostale.Voie=this.firstFormGroup.value.Voie_adresse;
this._AdressePostale.ID_Ville = this.VilleSelec.ID_Ville;

this.adresseservice.addAdressePostale(this._AdressePostale).subscribe(
adresse__=> { 
  this.PostID.push(adresse__)
  console.log(this.PostID[0]);
});

}

Aragorn
  • 5,021
  • 5
  • 26
  • 37
  • 1
    For more information ... I talk about this issue here: https://docs.google.com/presentation/d/1HKwcxnluNtFo_mi32y2wox8kQeclYKt21fuWHbDgF-U/edit?usp=sharing – DeborahK Jan 24 '19 at 19:08
  • Hello, thank you for the answer but for my project I need to know the ID of the object returned by the first service after subscribing it then use it in a second service. The problem is that I can't know when the first service is done. – SoufH Jan 26 '19 at 22:05