我发现在角度2中使用http的observable非常困难。
在下面的代码中,我成功地在控制台中打印了in method:
值。但是当我尝试打印时,Main:
为undefined
。
如何从Main
获取价值?
模板代码:
template:`
<input
class="form-control"
[formControl]="searchBox"
placeholder="Search Spotify artist" />
`
组件代码:
export class SpotifySearchComponent {
private searchBox = new FormControl();
constructor(private _http: Http){
}
ngAfterViewInit() {
var keyups = this.searchBox
.valueChanges
.debounceTime(200)
.map(searchTerm => {
this.getResults(searchTerm);
});
var subscription = keyups.subscribe(res => console.log("Main:" + res));
}
getResults(searchTerm){
console.log("in method:" + searchTerm);
return searchTerm;
}
}
答案 0 :(得分:2)
您在return
区块中缺少map
语句。
ngAfterViewInit() {
var keyups = this.searchBox
.valueChanges
.debounceTime(200)
.map(searchTerm => {
return this.getResults(searchTerm);
});
var subscription = keyups.subscribe(res => console.log("Main:" + res));
}
答案 1 :(得分:1)
您没有从map
函数返回任何内容。它应该是
.map(searchTerm => {
return this.getResults(searchTerm);
}
或
.map(searchTerm => this.getResults(searchTerm))