gpt4 book ai didi

javascript - 如何在 Angular 1 服务中设置和获取属性

转载 作者:行者123 更新时间:2023-12-03 04:04:34 25 4
gpt4 key购买 nike

我有以下类型的 Angular 1 服务。我正在尝试创建 getter 和 setter 方法来从不同的 Controller 访问变量。但是当我在 get 方法中 console.log 变量时,它是未定义的。

该服务随项目继承。我怎样才能以这种方式创建这些方法?谢谢。

;(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;
};

}());

更新:第一和第二 Controller 有不同的观点。在第一个 Controller 中我有:

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";
});

在第二个 Controller 中:

vm.WeeklyMeetingID = history.getWeeklyMeetingId();
console.log('get the id', history.getWeeklyMeetingId()) //Here it is undefined

最佳答案

这是正确的。请参阅此示例。

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>

关于javascript - 如何在 Angular 1 服务中设置和获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44617348/

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