【发布时间】:2017-11-29 10:57:50
【问题描述】:
我需要通过http.get 获取变量的值(必须是异步的):
@Injectable()
export class interaction{
private host: string="";
private port: string = "";
constructor(private http: Http) {
this.http.get("/interaction.json").subscribe((data: Response) => {
this.host = data.json().host;
this.port = data.json().port;
});
}
由于数据是异步的,我无法通过以下方法访问它们:
interact(data:Request): Promise<Response>{
return this.http.post("http://" + this.host + ":" + this.port, data)
.toPromise()
.then(data => data.json() as Response)
.catch(this.handleError);
}
所以,当我从另一个服务调用 interact() 时,host 和 port 是未定义的。
是否可以等待设置此变量,然后执行post 请求?我不想在interact() 中调用get,因为可以有很多函数使用这些变量。
如果有任何建议,我将不胜感激。
【问题讨论】:
-
我使用了一种方法来完成此任务,即不要订阅服务文件中的 http,取而代之的是,您可以在需要数据的地方订阅它。
-
我很好奇这种模式是否有帮助? stackoverflow.com/a/44051264/4614870
-
@Brian,获取该 Observable 的
null。
标签: javascript jquery angular angular2-services