gpt4 book ai didi

javascript - $当服务发生变化时观察服务

转载 作者:行者123 更新时间:2023-12-01 02:49:19 26 4
gpt4 key购买 nike

我想观察我的服务的变化,比如我的系统日志,当有人登录 getlogs 函数时必须触发如何实现这一点???

仪表板 Controller

function getLogs() {
return dataservice.getLogs().then(function (data) {
vm.logs = data;
return vm.logs;
});
}

dataservice.js

function getLogs() {
return $http.get('/api/timeLogs')
.then(success)
.catch(fail);

function success(response) {
return response.data;
}

function fail(e) {
return exception.catcher('XHR Failed for getPeople')(e);
}
}

我已经尝试过,但它不起作用

 $scope.$watch('dataservice.getLogs()', function () {
getLogs();
}, true);

最佳答案

这是可观察模式的案例,您订阅服务的更改

app.service('dataservice', function($http) {
var subscribers = [];
var addSubscriber = function(func){
subscribers.push(func);
}
var notifySubscribers = function(){
for(var i = 0; i< subscribers.length; i++){
subscribers[i](); //invoke the subscriber
}
};

var addLog = function(){
//let's say that the logs are added here

//then notify the subscribers that a new log has been added
notifySubscribers();
};

var getLogs = function() {
return $http.get('/api/timeLogs')
.then(success)
.catch(fail);

function success(response) {
return response.data;
}

function fail(e) {
return exception.catcher('XHR Failed for getPeople')(e);
}
};

return {
addSubscriber: addSubscriber,
addLog: addLog,
getLogs: getLogs
}
});

然后在您的 Controller 中向服务添加订阅者功能

dataservice.addSubscriber(function(){

console.log('new log added');
dataservice.getLogs();
});

注意:这也可以通过 RxJs 来完成图书馆

关于javascript - $当服务发生变化时观察服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47068370/

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