将HTTP请求返回给调用函数

时间:2018-03-21 20:24:48

标签: angular angular2-services

我希望从API服务HTTP_GET请求方法返回一个JSON对象,并将其放在变量this._test中。

搜索-component.ts

export class SearchComponent implements OnInit, OnChanges {
    ...    
    this.uiQuerySettings = new querySettings(this._api);
    this._test = this.uiQuerySettings.retrieveData("route3.json");
    ...
}

查询settings.ts

export class querySettings {
    constructor(private _api: ApiService) { }
    /* A generic method which accepts the name of the JSON configuration
     * file that is to be retrieved from the "server".  The address to
     * the server is found in the variable in the environment variable.
     */ 
    retrieveData(jsonFile: String): any {
    console.log("You are capturing data.");
    this._api.loadData(environment.jsonAddress + jsonFile).subscribe((results) => {
        if (!environment.DEBUG)
            console.log(results);
        return results;
    });
    }
}

" this._api"变量指向具有loadData方法的服务。 LoadData在提供的URL处执行简单的HTTP Get请求。我的目标是返回"结果"在query-settings.ts中找到并将其放在名为" this._test"的测试变量中。在search-component.ts中。我发现由于异步调用,this._test被设置为未定义的值。如何使用地图,并订阅以实现这一目标?我应该使用另一个函数来执行此操作吗?

如果这是一个重复我很抱歉,任何重定向都会非常感激。谢谢!

1 个答案:

答案 0 :(得分:2)

您需要从服务返回一个Observable并在您的组件中订阅它。

<强>查询settings.ts

import { Observable } from 'rxjs/observable';
export class querySettings {
    constructor(private _api: ApiService) { }
    /* A generic method which accepts the name of the JSON configuration
     * file that is to be retrieved from the "server".  The address to
     * the server is found in the variable in the environment variable.
     */
    retrieveData(jsonFile: String): Observable<any> {
        console.log("You are capturing data.");
        return this._api.loadData(environment.jsonAddress + jsonFile);
    }
}

搜索-component.ts

export class SearchComponent implements OnInit, OnChanges {
...
this.uiQuerySettings = new querySettings(this._api);
this.uiQuerySettings.retrieveData("route3.json").subscribe(results => {
    if (!environment.DEBUG)
        console.log(results);
    this._test = results;
});
...
}

如果您正在显示&#34; this._test&#34;在您的模板文件中,您可以使用&#34; Async pipe&#34;而不是上面提到的方式。