在调试应用程序问题的过程中,我在下面创建了简化组件。执行时会出现以下异常:
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;
}
}
答案 0 :(得分:1)
实际上,您应该在map
方法中使用switchMap
运算符而不是search
运算符,因为rawSearch
方法返回一个数组而不是一个可观察数据: / p>
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);
});
}