首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何通过服务传递数据?

如何通过服务传递数据?
EN

Stack Overflow用户
提问于 2018-07-10 20:08:44
回答 2查看 51关注 0票数 0

我需要保存来自一条路径的数据,然后在另一条路径中使用它。我试着用服务来做到这一点。

渠道服务

代码语言:javascript
运行
复制
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”

代码语言:javascript
运行
复制
        // Create new channel
        $scope.createNewChannel = function(){
            if ($scope.communityList.length != 0) {
                communityApiService.setCommunityIds($scope.communityList.join());
                $location.path('/channelUpdate');
            } else {
                // To do nothing
            }

        }

在路由'/channelUpdate‘中,我试图获取数据,但它是空字符串。

代码语言:javascript
运行
复制
console.log(channelApiService.getCommunityIds())

那么,如何将数据从一个控制器传递到另一个控制器呢?我发现了这个方法,但它不起作用。有什么想法吗?

EN

回答 2

Stack Overflow用户

发布于 2018-07-10 20:35:21

var _communityIds更改为this._communityIds或使用ES6类语法这里有一些引用classes MDN和更多samples。下面是一个演示,演示了您的类是什么样子

代码语言:javascript
运行
复制
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);
        }
}
票数 0
EN

Stack Overflow用户

发布于 2018-07-11 13:14:34

请检查下面的更新代码,而不是使用this

代码语言:javascript
运行
复制
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);
        }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51264803

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档