我需要保存来自一条路径的数据,然后在另一条路径中使用它。我试着用服务来做到这一点。
渠道服务
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())那么,如何将数据从一个控制器传递到另一个控制器呢?我发现了这个方法,但它不起作用。有什么想法吗?
发布于 2018-07-10 20:35:21
将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);
}
}发布于 2018-07-11 13:14:34
请检查下面的更新代码,而不是使用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);
}
}https://stackoverflow.com/questions/51264803
复制相似问题