ng5中的错误处理

时间:2018-05-02 11:20:17

标签: angular angular5

我是角色的新手,我使用版本5来开发一个小功能。 我有一个寄存器组件,因为我有一个注册方法,如下面的按钮点击事件调用。

register()
  {
    this.authService.register(this.model).subscribe(m=>{
      //console.log("Registeration Successful");
      this.alertify.success("Registeration Successful");
     }, error => {
       console.log(error);
       //console.log("Error while registering.");
       this.alertify.error(error);
     });
  }

在服务中我有两个方法成功调用API,但是我收到错误 CatchSubscriber.AuthService.errorHandler。这可能是由于捕获。我想要 从API中获取错误,我需要在用户界面中显示这些错误。

import { Injectable } from '@angular/core';

import { RequestOptions, Response } from '@angular/http';

import { HttpClient, HttpHeaders, HttpParams, HttpRequest, HttpDownloadProgressEvent, HttpErrorResponse } from '@angular/common/http';

import 'rxjs/add/operator/map';

import 'rxjs/add/operator/catch';

import { Observable } from 'rxjs/Observable';


register(model: any)
{
    const httpheaders = new HttpHeaders().set('Content-type','application/json');
    return this.httpClient.post(this.baseUrl + 'Register', model, {headers: httpheaders, responseType: 'json' }).catch(this.errorHandler);
}


private errorHandler(error: HttpErrorResponse)
{
  console.error(error.message);
  return Observable.throw(error.message || 'Server Error');
}

我面临的错误是

TypeError: Observable_1.Observable.throw is not a function
"CatchSubscriber.AuthService.errorHandler"
 at CatchSubscriber.error (catchError.js:105)

at MapSubscriber.Subscriber._error (Subscriber.js:134)

at MapSubscriber.Subscriber.error (Subscriber.js:108)
 at FilterSubscriber.Subscriber._error (Subscriber.js:134)

at FilterSubscriber.Subscriber.error (Subscriber.js:108)

我已经检查了其他linksotherLinks并尝试了同样但我仍然面临此错误

1 个答案:

答案 0 :(得分:0)

使用catchError而不是catch。您的注册方法如下:

register(model: any)
{
    const httpheaders = new HttpHeaders().set('Content-type','application/json');
    return this.httpClient
        .post(this.baseUrl + 'Register', model, {headers: httpheaders, responseType: 'json' })
        .pipe(catchError(this.errorHandler));
}