Search code examples
angularionic4

How do use a specific responses in a post return


I have a post to a Server which can return res {success: true}

enter image description here

In my post if I receive this response I am trying to active

this.successPost = true;

this.invitePost = false;

Only on this exact response. res {success: true}

My ts code always return the if and never the else on any res response.

ts

async sendInvite() {
  let formData = {
    "firstName" : this.data.firstName,
    "lastName" : this.data.lastName,
    "email" : this.data.email
  };
  this.httpClient.post<any>('https://8618' + formData, { 
    headers: { 'x-authorization-token': 'XXXXXXXXXX' }}   
    )
    .pipe(
      finalize(() => { })
    ).subscribe(
        res => {
          console.log ("res", res);
          let response = JSON.stringify(res);
            console.log ("response", response);
            if (res = {success: true} ) {
                this.presentToast(response);
                this.successPost = true;
                this.invitePost = false;
              } else {
                this.presentToast(response);
              }
        },
        (err: HttpErrorResponse) => {  // fire on offline
          console.log("err.error", err.error);
          this.presentToast(err.error);
        }  
  );
}

Solution

  • I would suggest you to not to stringify your response object and just use it as it is. And use equality operator(===) instead of assignment operator.

        async sendInvite() {
      let formData = {
        "firstName" : this.data.firstName,
        "lastName" : this.data.lastName,
        "email" : this.data.email
      };
      this.httpClient.post<any>('https://8618' + formData, { 
        headers: { 'x-authorization-token': 'XXXXXXXXXX' }}   
        )
        .pipe(
          finalize(() => { })
        ).subscribe(
            response => {
              console.log ("response ", response );
                if (res.success === true) {
                    this.presentToast(response);
                    this.successPost = true;
                    this.invitePost = false;
                  } else {
                    this.presentToast(response);
                  }
            },
            (err: HttpErrorResponse) => {  // fire on offline
              console.log("err.error", err.error);
              this.presentToast(err.error);
            }  
      );
    }