gpt4 book ai didi

javascript - Angularjs 1.5 - 使用服务的组件通信 - 异步变量操作?

转载 作者:行者123 更新时间:2023-11-28 05:49:46 25 4
gpt4 key购买 nike

我对 Angular 组件通信非常陌生。我正在使用 Angular 1.5.X 版本,并且使用工厂在组件之间共享数据。我面临一个问题,即服务变量的异步值在一段时间后刷新。

我知道一种解决方案是在非作用域变量上设置观察程序,但我认为我在这里遗漏了一些重要的东西。大家可以分享一下看法吗?

这是Service.js代码

Service.$inject = ['$http','$q'];

function Service($http,$q) {

this.$http = $http;
this.$q = $q;

};

Service.prototype.getTileCount = 0;

Service.prototype.getTileData = function(Url){

var deferred = this.$q.defer();

this.$http.get(Url)
.success(function(response){
Service.prototype.getTileCount = response.data.length;
console.log('data length :', Service.prototype.getTileCount);
deferred.resolve(response);
});

return deferred.promise;
};

这是组件 1 Controller 代码

function Component1Controller(Service) {

this.tileData ={};
var self = this;

var promise = Service.getTileData(this.sourceUrl);

promise.then(function(data) {

self.tileData = data;
Service.getTileCount = data.length;
console.log('This is tileData : '+ Service.getTileCount);
});

};

这是组件 2 Controller 代码

function Component2Controller(Service) {

var self = this;

console.log(Service.getTileCount);
// getting getTileCount = 0; After setting timeout function of 5 second I am able to get getTileCount value

};

最佳答案

问题是,Service.getTileCount 是异步更新的,这就是为什么它一开始是 0,然后在某个时刻发生变化的原因。我建议您简化您的服务并始终使用 getTileData 方法,该方法将是单一数据源。实现也将变得更简单:

function Service($http, $q) {
this._tileData = null;
this.$http = $http;
this.$q = $q;
}

Service.prototype.getTileData = function(Url) {

if (!this._tileData) {
this._tileData = this.$http.get(Url).then(function(response) {
return response.data;
}.bind(this));
}

return this._tileData;
};

请注意,它如何在“私有(private)”_tileData 属性中缓存图 block 响应。现在您始终可以依赖 getTileData 方法,无论您何时调用它都会返回数据:

function Component1Controller(Service) {

this.tileData = {};
var self = this;

Service.getTileData(this.sourceUrl).then(function(data) {
self.tileData = data;
console.log('This is tileData:', self.tileData.length);
});
};

function Component2Controller(Service) {
var self = this;
Service.getTileData(this.sourceUrl).then(function(data) {
console.log('tile count', data.length);
});
};

在这种情况下,不再需要Service.getTileCount

演示: http://plnkr.co/edit/3zE6VL4emXaLRx2nCRih?p=info

关于javascript - Angularjs 1.5 - 使用服务的组件通信 - 异步变量操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38168162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com