我是观察者的新手,并尝试了Christoph Burgdorf Observables in Angular2 blog的基本自动完成变体。运行此代码会产生:
EXCEPTION:TypeError:无法读取未定义的属性'Symbol(Symbol.iterator)'
在ingredientservice ... rawsearch中发出REST get调用之后。警报还会弹出[object Object]消息。我已经验证了端点运行正常。
非常感谢有关如何调试此内容的任何建议。
ingredientservice.ts 等待对文本字符串进行更改,对其进行去抖动并执行REST调用以从端点获取自动完成匹配。
import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/map';
@Injectable()
export class IngredientService {
endpoint_url: String = "http://localhost:5000/ingredient/";
results: Observable<Array<string>>;
constructor(private http: Http) { }
search(terms: Observable<string>, debounceDuration = 400) {
return terms.debounceTime(debounceDuration)
.distinctUntilChanged()
.switchMap(term => this.rawSearch(term));
}
getData: Object[];
rawSearch(term: string) {
console.log(term);
this.http.get(this.endpoint_url + term)
.subscribe(
res => {
this.getData = res.json();
console.log(this.getData);
return this.getData;
},
error => alert(error));
}
}
为了完整性我已经包含 ingredientsearch.ts
组件import {Component} from 'angular2/core';
import {Control} from 'angular2/common';
import {IngredientService} from './ingredientservice';
import {Observable} from 'rxjs/Observable';
@Component({
selector: 'ingredient-search',
template: `
<div>
<h2>Ingredient Search</h2>
<input type="text" [ngFormControl]="term"/>
<ul>
<li *ngFor="#item of items | async">{{item}}</li>
</ul>
</div>
`,
providers: [IngredientService]
})
export class IngredientSearch {
items: Observable<Array<string>>;
term = new Control();
constructor(private ingredientService: IngredientService) {
console.log("About to call service");
this.items = ingredientService.search(this.term.valueChanges);
}
}
更新了推荐修复的代码段。
rawSearch(term: string) {
this.getData = ([]);
this.http.get(this.endpoint_url + term)
.subscribe(
res => {
this.getData = res.json();
console.log(this.getData);
return this.getData;
},
error => {
alert(error);
});
return this.getData;
}
答案 0 :(得分:12)
视图绑定时未定义项目 - 在服务返回之前。将项初始化为空数组。或者在模板中使用Observable包装器和异步操作符。