在Observable链中传递后,类缺少方法

时间:2017-04-12 08:41:15

标签: javascript angularjs angular observable

在我通过Observable链传递后,我在angular2中遇到了一个奇怪的问题。

我总是收到错误:

EXCEPTION: f.mapToParams is not a function
ORIGINAL STACKTRACE:
TypeError: f.mapToParams is not a function
  at SafeSubscriber._next (filter.component.ts)
  ...
Uncaught TypeError: f.mapToParams is not a function
  at Safesubscriber._next (filter.component.ts)

这是我的编码:

filter.ts:

import { Params } from '@angular/router';

export class Filter {
  public text:String = '';
  public mapToParams():Params {
    let params:Params = {};
    // Do some mapping here...
    return params;
  }
}

filter.component.ts

import { Component, OnInit Output, EventEmitter } from '@angular/core';
import { Router, Params } from '@angular/router';
import { Filter } from './filter';
import { Observable, Subject } from 'rxjs/Rx';

export class FilterComponent implements OnInit {

  private _filter:Filter;
  private _filterStream = new Subject<Filter>();

  ngOnInit() {
    this._filter = new Filter();
    this._filterStream
      .debounceTime(300)
      .switchMap((f:Filter) => Observable.of(f))
      .subscribe((f:Filter) => {
        let params:Params = {};
        console.log(f.text);            // <-- No problem here
        // params = this._map(f);          // <-- This would work
        params = f.mapToParams();       // <-- Here occurs the error
      });
  }

  private _map(f:Filter):Params {
    // Do some mapping here
  }

  public onInputChanged(searchText:String):void {
    this._mergeFilter( {
      map(f:Filter) {
        f.text = searchText;
      }
    })
  }

  private _mergeFilter(callback:FilterMergeCallback):void {
    let f:Filter = JSON.parse(JSON.stringify(this._filter));
    callback.map(f);
    this._filterStream.next(f);
  }

}

我试图评论debounceTimeswitchMap声明,但没有成功。

在编码的不同点,可以毫无问题地调用filter.mapToParams方法。在我看来,Observable链从我的对象中剥离了所有方法。

这是我的角度配置:

  • @ angular / cli:1.0.0.-beta.32.3
  • @ angular / common:^2.4.0
  • @ angular / compiler ^2.4.0
  • @ angular / core ^2.4.0
  • rxjs:^5.1.0

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

我想我明白了:

我通过

将当前的_filter对象复制到新的过滤器变量中
JSON.parse(JSON.stringify())

这样,所有方法都会从新对象中剥离。

意思是,我必须找到一种克隆对象的新方法......

谢谢大家的回复!