【问题标题】:Angular2 service doesn't return result to Observable from http.get to componentAngular2 服务不会将结果从 http.get 返回到 Observable 到组件
【发布时间】:2017-04-17 04:09:40
【问题描述】:

我正在尝试使用 get 在 angular2 中设置视图。 一个 hava 一个组件和一个服务

在模板中我有一个搜索按钮,它会触发组件上的搜索功能

//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';

该服务确实在 console.log 上显示响应,但它不返回数据。 我搜索并关注了多个 tuts,但没有结果。我想我做得对,但忘记了一件小事,但我不知道是什么。

【问题讨论】:

    标签: angular rxjs observable


    【解决方案1】:

    如果您将=&gt;{} 一起使用,您需要明确地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();
        })
    

    【讨论】:

    • 谢谢,首先我写了 whiteout {} 但这在组件上不起作用。所以我添加了日志来检查响应并忘记了响应。我会在 2 分钟内接受你的回答。
    猜你喜欢
    • 2020-02-12
    • 2019-11-13
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    相关资源
    最近更新 更多