Angular 4-可观察到的捕获错误 [英] Angular 4 - Observable catch error

查看:67
本文介绍了Angular 4-可观察到的捕获错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Observable内部的捕获方法解决返回错误的问题?

How can I solve the problem of return with error, use the capture inside the Observable?

我想在catch中执行一个函数,以便在执行订阅之前进行一些验证.

I want to execute a function inside the catch, to do some validation before the subscribe is executed.

预先感谢您,非常感谢您的关注.

Thank you in advance, thank you very much for your attention.

-> .catch((e)=> {console.log(e)})发生错误

Error occurs in -> .catch( (e) => {console.log(e)} )

import { Injectable } from '@angular/core';
import { Headers, Http, ResponseOptions} from '@angular/http';
import { AuthHttp } from 'angular2-jwt';

import { MEAT_API } from '../app.api';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class  CompareNfeService {


    constructor(private http: AuthHttp) { }

    envirArquivos(order): Observable<any> {
        const headers = new Headers();
        return this.http.post(`${MEAT_API}compare/arquivo`, order,
        new ResponseOptions({headers: headers}))
        .map(response => response.json())
        .catch( (e) => {console.log(e)} );
    }
}

错误

/pxxxxxx/application/src/app/compare/service.ts中的

ERROR(28,17): 类型'(e:any)=> void'的参数不能分配给的参数 类型'((错误:任意,捕获:可观察)=> ObservableInput< {}>'.
不能将类型"void"分配给类型"ObservableInput< {}>".

ERROR in /XXXXXX/application/src/app/compare/service.ts (28,17): Argument of type '(e: any) => void' is not assignable to parameter of type '(err: any, caught: Observable) => ObservableInput<{}>'.
Type 'void' is not assignable to type 'ObservableInput<{}>'.

推荐答案

如果要使用Observablecatch(),则需要在将错误响应委托给方法之前使用Observable.throw()方法

If you want to use the catch() of the Observable you need to use Observable.throw() method before delegating the error response to a method

import { Injectable } from '@angular/core';
import { Headers, Http, ResponseOptions} from '@angular/http';
import { AuthHttp } from 'angular2-jwt';

import { MEAT_API } from '../app.api';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class CompareNfeService {


  constructor(private http: AuthHttp) {}

  envirArquivos(order): Observable < any > {
    const headers = new Headers();
    return this.http.post(`${MEAT_API}compare/arquivo`, order,
        new ResponseOptions({
          headers: headers
        }))
      .map(response => response.json())
      .catch((e: any) => Observable.throw(this.errorHandler(e)));
  }

  errorHandler(error: any): void {
    console.log(error)
  }
}

使用Observable.throw()为我工作

这篇关于Angular 4-可观察到的捕获错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆