【问题标题】:Angular 6 How to define a custom debug function in Angular ObservableAngular 6 如何在 Angular Observable 中定义自定义调试功能
【发布时间】:2019-04-09 21:22:54
【问题描述】:

刚刚在创建自定义调试时遇到问题

我已经按照教程进行自定义调试,下面是代码

import {Observable} from 'rxjs/index';
import {environment} from '../../environments/environment';

declare module 'rxjs/internal/Observable' {
  interface Observable<T> {
    debug: (...any) => Observable<T>;
  }
}

Observable.prototype.debug = (message: string) => {
  return this.do(
    (next) => {
      if (!environment.production) {
        console.log(message, next);
      }
    },
    (err) => {
      if (!environment.production) {
        console.error('ERROR >>', message, err);
      }
    },
    () => {
      if (!environment.production) {
        console.log('Completed - ');
      }
    }
  );
};

当我在服务中使用调试时,它给了我这个错误

this.httpClient.get(...).pipe(...).debug 不是函数 在 QuoteService.push../src/app/services/quote.service.ts.QuoteService.getQuote (quote.service.ts:19)

export class QuoteService {

  constructor(@Inject('BASE_CONFIG') private config,
              private httpClient: HttpClient) { }

  getQuote(): Observable<Quote> {
    const uri = `${this.config.uri}/quotes/${Math.floor(Math.random() * 10)}`;
    return this.httpClient.get(uri)
      .pipe(map((res: Quote) => res as Quote))
      .debug('quote: ');
  }
}

当我将调试包在 pipe() 中时,它只是说

ERROR ReferenceError: debug is not defined

我不知道如何解决这个问题,有人有想法吗?

感谢任何cmets

【问题讨论】:

  • 这不是你定义的 pipeable 操作符,它只是 Observable proto 上的一个方法。
  • 感谢您的评论!我通过定义一个受您的 cmets 启发的管道来弄​​清楚

标签: javascript angular angular6 angular-pipe angular-observable


【解决方案1】:

上面的调试方法来自 Angular 4,在 Angular 6 中我想出了一个更清晰和简单的方法

看代码:

import {pipe} from 'rxjs/index';
import {environment} from '../../environments/environment';
import {tap} from 'rxjs/internal/operators';

export const debug = (message: string) => pipe(
  tap(
    (next) => {
      if (!environment.production) {
        console.log(message, next);
      }
    },
    (err) => {
      if (!environment.production) {
        console.error('ERROR >>', message, err);
      }
    },
    () => {
      if (!environment.production) {
        console.log('Completed - ');
      }
    }
  )
);

然后可以通过在管道运算符中链接在任何需要的地方使用

getQuote(): Observable<Quote> {
    const uri = `${this.config.uri}/quotes/${Math.floor(Math.random() * 10)}`;
    return this.httpClient.get(uri)
      .pipe(debug('quote: '), map((res: Quote) => res as Quote));
  }

就这么简单

【讨论】:

    猜你喜欢
    • 2020-03-27
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 2019-08-23
    相关资源
    最近更新 更多