2015-09-04 57 views
9

使用在Android和Windows中執行的Ionic應用程序。帶有默認值的非現有屬性的角度服務

有服務,如離子的$ionicLoading,這是我們爲了覆蓋功能,在Windows正常工作:

angular.factory('$ionicLoading', function(){ 
    return { 
     show: function(){...} // custom implementation 
     hide: function(){...} // custom implementation 
    } 
}); 

但是,有一些我們不得不只覆蓋不打破應用等服務。 在這種情況下,提供不會做任何事的服務將非常有用。例如:

angular.factory('$ionicExampleService', function(){ 
    return { 
     *foo*: angular.noop // for operations 
     *bar*: promise // returns promise 
    } 
}); 

注:我知道這樣做的更好的方式是與離子的實施或提出一個之間選擇一個服務,但是這僅僅是學習的緣故。

理想將進一步持續,這將是宏偉的,以便能夠回到更防彈東西。就像通用的靈活服務:

angular.factory('$ionicPopup', function(){ 
    return /*magic*/; 
}); 

$ionicPopup.show({...}) // show was not defined 
    .then(foo); // won't break and will execute foo() 

這是可能的嗎?

+6

此問題在這裏有一個非常好的答案:http://stackoverflow.com/questions/6600868/set-default-value-of-javascript-object-attributes – sunny

+0

我擴大了一點在Sunny的答案,以幫助它適合情況。我也刪除了你的-1評級。 -C§ – CSS

回答

-3

使用var a = {};來聲明新變量。

0

使用基於對象屬性的每項任務進行評價,與此類似:

myVar = myObj.myPropVar === undefined ? "default replacement" : myObj.myPropVar; 

基本上你正在使用的,如果財產已經定義的檢查,替換默認值,如果它不是招」 t,並且如果它已經分配了它。

或者,您可以使用Sunny's linkback中全局函數的修改版本來定義所有這些屬性的默認值,您可能會認爲這些屬性在代碼中的特定點處未定義。

function getProperty(o, prop) { 
    if (o[prop] !== undefined) return o[prop]; 
    else if(prop == "foo") return "default value for foo"; 
    else if(prop == "bar") return "default value for bar"; 
    /* etc */ 
    else return "default for missing prop"; 
} 

希望幫助,

4

從我的理解,你需要重寫執行現有的服務。你可以用角色服務裝飾器來做到這一點。

服務裝飾器攔截服務的創建,允許它覆蓋或修改服務的行爲。裝飾器返回的對象可能是原始服務,也可能是一個新的服務對象,它替換或打包並委託給原始服務。

欲瞭解更多信息,你可以檢查角documentation。一個簡單的例子是:

app.factory('someService', function() { 
    return { 
     method1: function() { return '1'; } 
     method2: function() { return '2'; } 
    }; 
}); 

app.decorator('someService', function ($delegate) { 
    // NOTE: $delegate is the original service 

    // override method2 
    $delegate.method2 = function() { return '^2'; }; 

    // add new method 
    $delegate.method3 = function() { return '3'; }; 

    return $delegate; 
}); 

// usage 
app.controller('SomeController', function(someService) { 
    console.log(someService.method1()); 
    console.log(someService.method2()); 
    console.log(someService.method3()); 
}); 

編輯:問題 - 如何覆蓋服務中的每個方法?

var dummyMethod = angular.noop; 

for(var prop in $delegate) { 
    if (angular.isFunction($delegate[prop])) { 
     $delegate[prop] = dummyMethod; 
    } 
} 

我希望這可以幫助你。

+0

問題是我想重寫'someService'的每個方法,而不知道他的實現。像'$ delate.everyMethod = function(){return'hello world!'; };' – fuxes