我是Observable的新手,并在Angular2博客中尝试了Christoph Burgdorf的Observables的基本自动完成版本。运行此代码将产生:
例外:TypeError:无法读取未定义的属性'Symbol(Symbol.iterator)'
发出REST后,可以在Ingredientservice ... rawsearch中调用。警报还会弹出并带有[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));
}
}
为了完整起见,我已经包括了component 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;
}
绑定视图时-在服务返回之前,项是未定义的。将项目初始化为空数组。或在模板中使用Observable包装器和async运算符。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句