Javascript Can';t访问角度服务中的对象属性

Javascript Can';t访问角度服务中的对象属性,javascript,angularjs,service,Javascript,Angularjs,Service,我正在尝试使用属性通道设置名为channelid的对象。然而,当我试图访问它时,我返回对象{} 服务 function Service($http){ var service = this; var channelid = {}; // Set channel ID service.SetChannelID = function(id){ channelid.channel = id; }; // Get Channel Id service.GetCha

我正在尝试使用属性通道设置名为channelid的对象。然而,当我试图访问它时,我返回对象{}

服务

function Service($http){
  var service = this;
  var channelid = {};

  // Set channel ID
  service.SetChannelID = function(id){
    channelid.channel = id;
  };

  // Get Channel Id
  service.GetChannelID = function(){
    return channelid;
  };
控制器

// Set channel id
Service.SetChannelID(channel.id);

// Retrieve channel id
var channelID = Service.GetChannelID();
当我尝试访问它时

console.log(channelID.channel);
它打印未定义的内容

如果我打印

console.log(channelID);
它打印对象{}

>Object
  channel:"C3NBGTQJD"
  __proto__: Object 

非对象{channel:“C3NBGTQJD”}

作为参考,您可以按照此小提琴进行操作

"http://jsfiddle.net/ADukg/9158/"
服务

  myApp.service('myService', function(){
  var channelObj={};
  var service = this;

  service.setChannelId = function(id) {
    channelObj.channel = id;
  };

  service.getChannel = function() {
    return channelObj;
  }

});
控制器

$scope.setChannelId = function (id) {
        myService.setChannelId(id);
}

$scope.getChannelId = function() {
        var channelObj = myService.getChannel()
        alert(channelObj.channel);
}
模板

<div ng-controller="MyCtrl">
  <button ng-click="setChannelId(5)">
    Set Channel
  </button>
  <button ng-click="getChannelId()">
    Get Channel
  </button>

</div>

设置频道
获取频道

因为
channelid
服务
函数的私有变量。。您无法通过
服务
函数实例进行访问…您只能通过
getter
setter
获取您已经拥有
服务的值。SetChannelID
似乎没有定义
SetChannelID
仅在
Service
的实例上定义,而不是在构造函数本身上定义。Service是类/构造函数。你创建了它的一个实例吗?var服务=新服务();然后调用这些方法?我试图实现的是:var channelObj=myService.getChannel();函数GetChannelDataById(channelObj.channel);函数GetChannelDataById(id){//do something}