【发布时间】: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以实现其余逻辑