M
M
Maxim Tarabrin2017-09-04 14:11:57
Angular
Maxim Tarabrin, 2017-09-04 14:11:57

How to throw an error to a component?

So at the moment I have a login component, which is engaged in obtaining a token from the backend through the authenticationService service. In the service, I have a catch that returns an error to the handleError function, it receives an error: Response. There I do something with it, well, let's just output it to the console. And then I would like the component to throw the error back and display the text to the user in the snackBare. In handleError I do return Observable.throw('Error!') But it doesn't throw what I wanted) I'll attach the code below:
AuthenticationService

logInSystem(login: string, password: string): Observable<{}>{
    let urlAuth = 'auth';
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers, method: "post" });
    return this.http.post(this._url+urlAuth,{login,password},options)
      .map((res:Response) => res.json())
      .catch(this.handleError);
  }

  private handleError(error: any){
    let resMsg = '';
    if(error.json().username){
      resMsg = 'Вы неверно ввели логин или пароль';
    }
    return Observable.throw(resMsg);
  }

Login Component(Function called on ngSubmit)
doLogin(event){
    this.authenticationService.logInSystem(this.loginForm.value['login'],this.loginForm.value['password']).subscribe(
      data => {
        console.log(data);
      },
      err => {
        this.snackBar.open(err,'Закрыть',{
          duration: 3000,
        });
      }
    );
    this.loginForm.reset();
  }

Error in console:
TypeError: __WEBPACK_IMPORTED_MODULE_2_rxjs_Observable__.Observable.throw is not a function
    at CatchSubscriber.webpackJsonp.../../../../../src/app/authentication.service.ts.AuthenticationService.handleError [as selector] (authentication.service.ts:30)
    at CatchSubscriber.webpackJsonp.../../../../rxjs/operator/catch.js.CatchSubscriber.error (catch.js:104)
    at MapSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber._error (Subscriber.js:128)
    at MapSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber.error (Subscriber.js:102)
    at XMLHttpRequest.onLoad (http.es5.js:1231)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.es5.js:3881)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424)
    at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (zone.js:192)
    at ZoneTask.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:499)

I'm forwarding something else. How to do error forwarding?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question