简体   繁体   English

Angular2服务不会将结果从http.get返回到Observable到组件

[英]Angular2 service doesn't return result to Observable from http.get to component

I am trying to use a get to set a view in angular2. 我正在尝试使用get在angular2中设置视图。 A hava a component and a service 组件和服务

in the template I have a seachbutton, that fires the search funtion on the component 在模板中,我有一个seachbutton,它触发了组件上的搜索功能

//component
searchResult : SearchData[];
searchData(){
    this.search.geSearchResultPart1(this.form.searchterm)
        .subscribe(
            searchresult => {
                    this.searchResult = searchresult
                    console.log(  searchresult ); // undefined
                }, 
                err => {
                   console.log(err);
                });
}

In the service i do 我在服务中

 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'));
}

I also included (and the necessary other imports) 我还包括了(以及其他必要的进口品)

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

The service does show response on the console.log, but it doesn't return the data. 该服务确实在console.log上显示了响应,但是不返回数据。 I searched and followed multiple tuts, but no result. 我搜索并跟踪了多个提示,但没有结果。 I think i am doing it wright, but forgetting a small thing, but i don't know what. 我想我做的不错,但是忘记了一件小事,但是我不知道是什么。

If you use => with {} you need to explicitly return 如果将=>{} ,则需要显式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();
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM