简体   繁体   中英

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. A hava a component and a service

in the template I have a seachbutton, that fires the search funtion on the component

//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. 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 this.http.get(fullURL)
    .map((res: Response) => { 
        res.json().data as SearchData[]
        console.log(res.json()); // Shows an array with objects
        return res.json();
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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