Interface based programming with TypeScript, Angular 2 & SystemJS

前端 未结 4 1638
抹茶落季
抹茶落季 2021-01-05 05:22

I\'m currently trying to clean up some code in order to program against interfaces rather than against implementations but can\'t figure out how to.

To be more speci

4条回答
  •  难免孤独
    2021-01-05 06:06

    You have to keep in mind that your class may (and should) depend on abstractions, but there is one place where you can't use abstraction : it's in the dependency injection of Angular.

    Angular must know what implementation to use.

    Example :

    /// 
    
    module MyModule.Services {
        "use strict";
    
        export class LocalStorageService implements ILocalStorageService {
            public set = ( key: string, value: any ) => {
                this.$window.localStorage[key] = value;
            };
    
            public get = ( key: string, defaultValue: any ) => {
                return this.$window.localStorage[key] || defaultValue;
            };
    
            public setObject = ( key: string, value: any ) => {
                this.$window.localStorage[key] = JSON.stringify( value );
            };
    
            public getObject = ( key: string ) => {
                if ( this.$window.localStorage[key] ) {
                    return JSON.parse( this.$window.localStorage[key] );
                } else {
                    return undefined;
                }
            };
    
            constructor(
                private $window: ng.IWindowService // here you depend to an abstraction ...
                ) { }
        }
        app.service( "localStorageService",
            ["$window", // ... but here you have to specify the implementation
                Services.LocalStorageService] );
    }
    

    So in your test you can use mocks easily as all your controllers/services etc depend on abstractions. But for the real application, angular needs implementations.

提交回复
热议问题