Home > OS >  "If" condition within Subscribe - Angular
"If" condition within Subscribe - Angular

Time:03-24

I would like to add a toastr notification within my errorNotification function so that it would show a message if the input the user has provided is invalid. I have created customised statuses and messages in the API that I would like to display in the content of the toastr.

Is there a way I can do an "if" statement within my function such that I can do something like this:

async errorNotification(task: Task) {
    this.taskService
      .addTask(task)
      .subscribe((response) =>
        if (response.body.data.result === 'fail') {
          this.toastr.error(response.body.data.message)
        }
        else {
          this.toastr.success(response.body.data.message)
        }
      );
  }

This is my current code:

async errorNotification(task: Task) {
    this.taskService
      .addTask(task)
      .subscribe((response) =>
        console.log(response.body.data.result, response.body.data.message)
      );
  }

CodePudding user response:

You can do the check you need inside the body of the subscription, with braces {} like this :

.subscribe((response) =>
// Add next line
{
    if (response.body.data.result === 'fail') {
      this.toastr.error(response.body.data.message)
    }
    else {
      this.toastr.success(response.body.data.message)
    }
// Add next line
  }
  );

You could find more informations here

I prefer to use await for clarity purpose :

const response = await this.taskService.addTask(task);
if (response.body.data.result === 'fail') {
   this.toastr.error(response.body.data.message);
} else {
   this.toastr.success(response.body.data.message);
}

CodePudding user response:

Why do you want to wait for the response of addTask? Instead of treating the error right there?

addTask(task: Task): Observable<any> {
  return someAsyncCall(task).pipe(
     tap((response) => 
       response.body.data.result === 'fail'
        ? this.toastr.error(response.body.data.message)
        : this.toastr.success(response.body.data.message)
      )
  );
}

And with this approach you don't need an aditional function

  • Related