Reputation: 2949
I have the following type of angular 1 service. I'm trying to create getter and setter method to get access to a variable from different controllers. But when I console.log the variable in the get method, it is undefined.
This service is inherited with the project. How could I create these methods in this way? Thanks.
;(function(){
angular.module( "MeetingApp" )
.factory( 'history', history );
history.$inject = [ '$http' ];
function history( $http ){
var historyService = {
//other methods
createHistory: createHistory
setWeeklyMeetingId: setWeeklyMeetingId,
getWeeklyMeetingId: getWeeklyMeetingId
}
function setWeeklyMeetingId(id) {
this.weeklyMeetingId = id;
}
function getWeeklyMeetingId() {
return this.weeklyMeetingId;
}
return historyService;
};
}());
Updated: First and second controllers have different views. In the first controller I have:
history.generateNewWeeklyMeeting(projectOrproduct)
.then(meeting => {
history.setWeeklyMeetingId(meeting.id);
console.log('id',history.getWeeklyMeetingId()); //here I get the id
return meeting;
})
.then(meeting => {
location.href = siteURL + "/new-team-meeting";
});
In the second controller:
vm.WeeklyMeetingID = history.getWeeklyMeetingId();
console.log('get the id', history.getWeeklyMeetingId()) //Here it is undefined
Upvotes: 0
Views: 52
Reputation: 318
Can you check whether you run vm.WeeklyMeetingID = history.getWeeklyMeetingId(); after you run that set method? Maybe you run get before you set it. As you call set inside a asynchronous call it takes sometime to get the response and run inside.
Upvotes: 0
Reputation: 17299
It's correct. see this sample.
app = angular.module("myApp", []);
app.controller("myCtrl", function($scope,history) {
history.setWeeklyMeetingId(10);
});
app.controller("myCtrl2", function($scope,history) {
var vm = this;
vm.WeeklyMeetingID = history.getWeeklyMeetingId();
});
app.factory('history', history);
history.$inject = ['$http'];
function history($http) {
var historyService = {
setWeeklyMeetingId: setWeeklyMeetingId,
getWeeklyMeetingId: getWeeklyMeetingId
}
function setWeeklyMeetingId(id) {
this.weeklyMeetingId = id;
}
function getWeeklyMeetingId() {
return this.weeklyMeetingId;
}
return historyService;
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
</div>
<div ng-controller="myCtrl2 as vm">
{{vm.WeeklyMeetingID}}
</div>
</div>
Upvotes: 1