我需要保存一条路线中的数据并在另一条路线中使用它。我试图通过服务来做到这一点。
频道服务
function channelApiService($rootScope, $http, $cookies){
var _communityIds = '';
return{
setCommunityIds: function(ids){
_communityIds = ids;
},
getCommunityIds: function(){
return _communityIds;
},
channelCreate: function(callback){
var token = $cookies.get('token');
var data = {
"token": token,
"communities_id": this.getCommunityIds(),
}
$rootScope.httpRequest('POST', '/channel/create', data, callback);
},
}
}
}
在路线“ / channelsList”中
// Create new channel
$scope.createNewChannel = function(){
if ($scope.communityList.length != 0) {
communityApiService.setCommunityIds($scope.communityList.join());
$location.path('/channelUpdate');
} else {
// To do nothing
}
}
在路由“ / channelUpdate”中,我尝试获取数据,但是它是空字符串。
console.log(channelApiService.getCommunityIds())
那么,如何将数据从一个控制器传递到另一个?我找到了这种方法,但是它不起作用。有什么想法吗?
答案 0 :(得分:0)
将var _communityIds
更改为this._communityIds
或使用ES6类语法
这里有一些参考文献classes MDN
以及更多samples。这是一个演示,您的班级样子
class ChannelApiService {
constructor($rootScope, $http, $cookies) {
this._communityIds = '';
}
setCommunityIds(ids) {
_communityIds = ids;
}
getCommunityIds() {
return _communityIds;
}
channelCreate(callback) {
var token = $cookies.get('token');
var data = {
"token": token,
"communities_id": this.getCommunityIds(),
}
$rootScope.httpRequest('POST', '/channel/create', data, callback);
}
}
答案 1 :(得分:0)
请使用下面的更新代码代替var
,请使用this
class ChannelApiService {
constructor($rootScope, $http, $cookies) {
this._communityIds = '';
}
setCommunityIds(ids) {
this._communityIds= ids;
}
getCommunityIds() {
return this._communityIds;
}
channelCreate(callback) {
var token = $cookies.get('token');
var data = {
"token": token,
"communities_id": this.getCommunityIds(),
}
$rootScope.httpRequest('POST', '/channel/create', data, callback);
}
}