首页 > 解决方案 > 如何等到我得到 Angular 4 的 HTTP 的结果?

问题描述

export class PropertiesService {
 getCommonProperties():any{
        let URL: string = "/xxxx/yyyyy";
        let headers = new Headers();
        let options = new RequestOptions({ headers });
        options.method = GET;
        return this.http.request(URL, options).map(response => {
            {
                console.log("response ", response.json());
                return response.json();
            };
    }
}

/**************************/
export class A {

this.commonProperties.setPropertiesMap(
this.propertiesService.getCommonProperties().subscribe(result => 
{ return result;})
);
//logic to iterate commonPropertiesMap
}

/*PropertiesMap 是一个存储一些属性的键值对的映射,我有一个名为 propertiesService 的服务,我从服务器获取属性流,我必须将结果设置到属性映射中。我从服务器获取结果(我可以在控制台中看到它),因为控件正在传递到下一步,甚至在我从服务器获得响应之前,所以会抛出 PropertiesMap 不可迭代的错误。有人可以帮助我保持控制的逻辑,直到我从 HTTP 请求中获得结果并将值设置到 PropertiesMap 中,然后遍历地图?*/

标签: angularangular4-httpclient

解决方案


将依赖于结果的任何内容放在 subscribe 函数中,或者从 subscribe 函数中调用的函数中,如下所示:

this.propertiesService.getCommonProperties().subscribe(result => {
    // Do you logic that relies on the results within here
    this.commonProperties.setPropertiesMap(result);
    return result;
})

推荐阅读