Show error if empty


#1

Hi,

Hi to show an error and don’t POST if there is no data ??

  declarerSinistre(){
    //http://michael.laffargue.fr/blog/2016/04/17/angularjs2-send-http-post-request-with-parameters-to-php/
    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    this.getData();
    
    var params = 'ClientId='+this.data.id+'&NomConducteur='+this.userData.NomConducteur+'&TelConducteur='+this.userData.TelConducteur+'&CinConducteur='+this.userData.CinConducteur+'&latitude='+this.la+'&longitude='+this.lo;
    this.http.post(this.apiSinistre, params , {headers: headers})
      .subscribe(
        data => this.afficherAlert('Réussite','Sinistre Déclaré'),
        err => this.afficherAlert('Erreur','Sinistre Non Déclaré')
      );
  }

Because it doesn’t work with this code, it send an undefined value


#2

I don’t understand exactly what you are trying to do, but checking if sth is there is easy:

if( typeof( variable ) !== "undefined"){
// do sth
}

if you are using data from a form then I would also check for string length:

if( typeof( variable ) === "string" && variable.length > 0){
// do sth
}

and with a form you might also wanna check this out: https://angular.io/guide/form-validation

You could chain the conditions to check all vars with && like:

if( ( typeof( this.data.id ) === "string" && this.data.id.length > 0 ) 
    && ( typeof( this.userData.NomConducteur ) !== "undefined") 
    && ( typeof( this.userData.TelConducteur ) === "string" && this.userData.TelConducteur.length > 0 ) 
    && ( typeof( this.userData.CinConducteur ) === "string" && this.userData.CinConducteur > 0 ) 
    && ( typeof( this.la ) !== "undefined") 
    && ( typeof( this.lo ) !== "undefined") ){
// do the request
} else {
//error
}

I don’t know if I got your datatypes right - sadly I don’t speak you language