AngularJS 仅在尚未设置时从 API 获取值

AngularJS get value from API only if not already set

我有服务可以从 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 将 return 值之前多次请求该值怎么办?我可以避免多次调用 API 吗?

可以缓存承诺:

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 请求。