【问题标题】:EXCEPTION: Cannot find a differ supporting object 'test2' in [items | async例外:在 [items | 中找不到不同的支持对象“test2”异步
【发布时间】:2016-04-04 20:21:40
【问题描述】:

在调试应用程序问题的过程中,我创建了下面的简化组件。执行时出现如下异常:

ingredient2service.ts:24 ["test1", "test2"]
angular2.dev.js:23093 EXCEPTION: Cannot find a differ supporting object 'test2' in [items | async in Ingredient2SearchComponent@5:12]
angular2.dev.js:23083 ORIGINAL EXCEPTION: Cannot find a differ supporting object 'test2'

我的猜测是它与 rawSearch 返回的数据格式有关,但是我无法弄清楚我做错了什么。任何建议将不胜感激!

ingredient2search.component.ts

import {Component} from 'angular2/core';
import {Control} from 'angular2/common';
import {Ingredient2Service} from './ingredient2service';
import {Observable} from 'rxjs/Observable';

@Component({
  selector: 'ingredient-search',
  providers: [Ingredient2Service],
  template: `
    <div>
      <h2>Ingredient2 Search</h2>
      <input type="text" [ngFormControl]="term"/>
      <ul>
        <li *ngFor="#item of items | async">{{item}}</li>
      </ul>
    </div>
  `
})
export class Ingredient2SearchComponent {
  items: Observable<Array<string>>;
  term = new Control();
  constructor(private ingredient2Service: Ingredient2Service) {
    this.items = ingredient2Service.search(this.term.valueChanges);
  }
}

ingredient2service.ts

import {Injectable} from 'angular2/core';
import {URLSearchParams, Http, HTTP_PROVIDERS} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';


@Injectable()
export class Ingredient2Service {
getData = [];

  constructor(private http: Http) { }
  search(terms: Observable<string>, debounceDuration = 400) {
    return terms.debounceTime(debounceDuration)
      .distinctUntilChanged()
      .switchMap(term => this.rawSearch(term));
  }

  rawSearch(term: string) {
    var getData = new Array();
    this.getData = ["test1", "test2"];
    console.log(this.getData);
    return this.getData;
  }
}

【问题讨论】:

    标签: angular


    【解决方案1】:

    事实上,您应该在search 方法中使用map 运算符而不是switchMap 运算符,因为rawSearch 方法返回一个数组而不是可观察对象:

    search(terms: Observable<string>, debounceDuration = 400) {
      return terms.debounceTime(debounceDuration)
        .distinctUntilChanged()
        .map(term => this.rawSearch(term));
    }
    

    如果rawSearch 方法返回一个可观察对象,它可以与您的代码一起正常工作。这是一个带有原始 observable 的示例:

    rawSearch(term: string) {
      var getData = new Array();
      this.getData = ["test1", "test2"];
      console.log(this.getData);
      return Observable.create((observer) => {
        observer.next(this.getData);
      });
    }
    

    【讨论】:

    • 将 observable 添加到 return 效果很好!谢谢你。当术语在去抖动期内发生变化时,我不需要保留 switchmap 以取消订阅以前的呼叫吗?
    猜你喜欢
    • 2016-04-22
    • 2020-08-29
    • 1970-01-01
    • 2020-02-08
    • 2019-09-08
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多