Angular2服务不会返回从http.get到组件Observable
问题描述:
我想用get来在angular2中设置一个视图。 一个HAVA的组件和服务Angular2服务不会返回从http.get到组件Observable
模板我有一个seachbutton,触发该搜索funtion组件
//component
searchResult : SearchData[];
searchData(){
this.search.geSearchResultPart1(this.form.searchterm)
.subscribe(
searchresult => {
this.searchResult = searchresult
console.log( searchresult); // undefined
},
err => {
console.log(err);
});
}
在服务我做
getSearchResultPart1(searchWord : string) : Observable<SearchData[]> {
let fullURL = 'url=http://domain.nl/searchData.php?q='+searchWord;
return this.http.get(fullURL)
.map((res: Response) => {
res.json().data as SearchData[]
console.log(res.json()); // Shows an array with objects
})
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
我也包括在内(和必要的其他进口)
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
服务e在console.log上显示响应,但它不返回数据。 我搜查了多次,但没有结果。我认为我在做这件事,但忘记了一件小事,但我不知道是什么。
答
如果使用=>
与{}
你需要明确return
return this.http.get(fullURL)
.map((res: Response) => {
res.json().data as SearchData[]
console.log(res.json()); // Shows an array with objects
return res.json();
})
谢谢,首先我写的白化{}但这并没有在组件上工作。所以我添加了日志来检查响应并忘记了响应。我会在2分钟内接受你的回答。 – user1664803