2017-01-13 40 views
0

我試圖設置一個名爲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 

不反對{信道: 「C3NBGTQJD」}

+1

因爲'channelid'是。你無法通過訪問'Service'功能私有變量'服務'功能實例...你co uld僅通過'getter'&'setter'獲得該值,您已經擁有 –

+0

'Service.SetChannelID'似乎沒有定義。 「SetChannelID」僅在「Service」的實例上定義,而不在構造函數本身上定義。 – 4castle

+0

服務是一個類/構造函數。你創建了它的一個實例嗎? var service = new Service();然後調用方法? – Hoyen

回答

0

對於參考你可以按照這個小提琴

"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> 
+0

我想要實現的是: var channelObj = myService.getChannel(); 函數GetChannelDataById(channelObj.channel); 函數GetChannelDataById(id){ //做某事 } – payucon