Euridice01
Euridice01

Reputation: 2568

Can I use a snackbar inside my service?

I want to get error details from my service call that calls an api if an error occurs.

E.g. if http error that comes back is 422, I want to display a user friendly message.

So, here's my service class:

@Injectable()
export class TransactionService {

  private baseUrl = 'http://foo.bar/api';
  private body;
  private headers;
  private options;

  constructor(private http: HttpClient, private snackBar: MatSnackBar) {

  }

  openSnackBar(message: string) {
    this.snackBar.open(message, null, {duration: 5000});
  }

  errorHandler(error: HttpErrorResponse) {

    console.log(error.status);
    if (error.status === 422) {
      this.openSnackBar('Number already exists');
    } else {
    return Observable.throw(error.message || 'Server Error');
    }
  }

  SubmitTransaction(transactionRequest: ITransactionRequestObj): Observable<TransactionResponse> {
    this.body =  JSON.stringify(transactionRequest);
    this.headers = new HttpHeaders().set('Content-Type', 'application/json');
    this.headers.append('Accept', 'application/json');
    this.options = new RequestOptions({headers: this.headers});
    console.log(JSON.stringify(transactionRequest));
    return this.http.post<TransactionResponse>(this.baseUrl + '/transactions/new',  this.body, this.options)
                .catch(this.errorHandler);
  }

}

I did a console.log and I do get the correct error status number back when there's a 422 error. However, the snackbar won't pop up because I get this error instead:

core.js:1448 ERROR TypeError: this.openSnackBar is not a function
    at CatchSubscriber.TransactionService.errorHandler [as selector] (transaction.service.ts:49)
    at CatchSubscriber.error (catchError.js:105)
    at MapSubscriber.Subscriber._error (Subscriber.js:131)
    at MapSubscriber.Subscriber.error (Subscriber.js:105)
    at FilterSubscriber.Subscriber._error (Subscriber.js:131)
    at FilterSubscriber.Subscriber.error (Subscriber.js:105)
    at MergeMapSubscriber.OuterSubscriber.notifyError (OuterSubscriber.js:24)
    at InnerSubscriber._error (InnerSubscriber.js:28)
    at InnerSubscriber.Subscriber.error (Subscriber.js:105)
    at XMLHttpRequest.onLoad (http.js:2283)

Is it because I shouldn't/can't use snackbar inside my service (only components?)?

The same snackbar code works fine inside my component but I can't get the error status inside my component.

Here's the service call inside my component class as well:

this._transactionService.SubmitTransaction(this.transactionObj).subscribe(data => {
        if (data._errorDetails._status === '201') {
          //do some action 
        }
      }, (err) => {
        console.log(err);
        if (err.status === 422) { //also tried this inside my component err.status is undefined. However err is the server error message.
        //do some action 
        }
      });

Upvotes: 1

Views: 1532

Answers (1)

yurzui
yurzui

Reputation: 214047

I assume you need to bind correct this context to do it working:

.catch(this.errorHandler.bind(this));

Or you can also use these options:

.catch((e) => this.errorHandler(e));

or local fat arrow function:

errorHandler = (error: HttpErrorResponse) => {
  ...
}

For more details see:

Upvotes: 2

Related Questions