【问题标题】:How to wait untill I get the results for HTTP get in angular 4? [duplicate]如何等到我得到 Angular 4 的 HTTP 的结果? [复制]
【发布时间】:2018-07-30 17:31:28
【问题描述】:
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 中,然后遍历地图? */

【问题讨论】:

  • 将任何依赖于结果的内容放在subscribe 函数中,或者从订阅函数中调用的函数中
  • 对不起,我没看懂,能不能详细点?
  • 我在下面添加了一个答案。我不完全确定 setPropertiesMap 函数期望什么,但您应该了解总体思路
  • 把你的逻辑放在你的订阅中得到结果: this.propertiesService.getCommonProperties().subscribe(result => // 用结果做东西; // 迭代 commonPropertiesMap 的逻辑 } ) );

标签: angular angular4-httpclient


【解决方案1】:

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

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

【讨论】:

  • /*我已经改了代码但是没有运气*/ public getCommonProperties(): CommonProperties { if (this.commonProperties == null) { this.commonProperties = new commonProperties(); this.propertiesService.getCommonProperties().subscribe(result => { this.commonProperties.commonPropertiesMap = result; }); console.log("map", this.commonProperties.commonPropertiesMap); } 返回 this.commonProperties; }
  • @tejasri 因为代码是异步的,所以你的返回值永远是undefined
  • 知道了,非常感谢
【解决方案2】:

你必须把迭代的逻辑放在订阅而不是外面

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

【讨论】:

    猜你喜欢
    • 2021-06-30
    • 1970-01-01
    • 2020-09-18
    • 2022-10-23
    • 1970-01-01
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多