【问题标题】:AngularJS get value from API only if not already setAngularJS 仅在尚未设置的情况下从 API 获取值
【发布时间】:2020-02-16 00:23:21
【问题描述】:

我有服务从 API 获取一些数据并将它们提供给应用程序。 像这样的简单函数:

getEnvironmentStatus() {
    var _this = this;
    var req = {
        method: "GET",
        url: "/api/system/hosting",
        headers: {},
        data: {}
    }
    return _this.$http(req);
}

在我的其他地方:

determineHostingEnv() {
    var _this = this;
    this.$env.getEnvironmentStatus()
    .then(function(response){
        _this.EnvHositng = response.data.cloud_hosted;
     }, function(error) {
    }); 
}

如果我在其他地方(其他控制器)需要相同的信息,我需要再次调用 api。

如何使 getEnvironmentStatus() 函数只调用一次 API 并将数据存储在局部变量中,以便在下次请求时为该变量提供服务,而不是调用 API? 另外,如果在第一个 API 返回值之前该值会被请求几次怎么办?我可以阻止多次调用该 API 吗?

【问题讨论】:

    标签: angularjs promise angular-promise


    【解决方案1】:

    可以缓存承诺:

    httpPromiseCache = null;
    
    getEnvironmentStatus() {
        var _this = this;
        var req = {
            method: "GET",
            url: "/api/system/hosting",
            headers: {},
            data: {}
        }
        if (!_this.httpPromiseCache) _this.httpPromiseCache = _this.$http(req);
        return _this.httpPromiseCache;
    }
    

    服务只会执行一次 HTTP 请求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-23
      • 1970-01-01
      • 2018-02-21
      • 2019-12-26
      • 2016-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多