【问题标题】:Return HTTP request back to calling function将 HTTP 请求返回给调用函数
【发布时间】:2018-03-22 05:33:18
【问题描述】:

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

search-component.ts

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

query-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 中找到的“结果”,并将其放在 search-component.ts 中名为“this._test”的测试变量中。我发现由于异步调用,this._test 被设置为未定义的值。一个人如何利用地图并订阅来实现这一点?我应该使用其他函数来执行此操作吗?

如果这是重复的,我很抱歉,任何重定向将不胜感激。谢谢!

【问题讨论】:

  • 您将无法像异步机制一样做到这一点。您可以从 retrieveData 返回可观察对象,以便 this._test 成为可观察对象并订阅 this._test 以实现其余逻辑

标签: angular angular2-services


【解决方案1】:

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

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

search-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;
});
...
}

如果您在模板文件中显示“this._test”,您可以使用“Async pipe”代替上述方式。

【讨论】:

    猜你喜欢
    • 2015-12-28
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多