Interface based programming with TypeScript, Angular 2 & SystemJS

前端 未结 4 1619
抹茶落季
抹茶落季 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 05:45

    TypeScript doesn't produce any symbols for interfaces, but you're going to need a symbol of some sort to make dependency injection work.

    Solution: use OpaqueTokens as your symbol, assign a class to that token via the provide() function, and use the Inject function with that token in the constructor of your class.

    In the example here, I've assumed that you want to assign PostsServiceImpl to PostsService in the Posts component, because it's easier to explain when the code is all in the same place. The results of the provide() call could also be put into the second argument of angular.bootstrap(someComponent, arrayOfProviders), or the provide[] array of a component higher up the hierarchy than the Posts component.

    In components/posts/posts.service.ts:

    import {OpaqueToken} from "@angular/core";
    export let PostsServiceToken = new OpaqueToken("PostsService");
    

    In your constructor:

    import {PostsService, PostsServiceImpl, PostsServiceToken} from 'components/posts/posts.service';
    import {provide} from "@angular/core";
    @Component({
        selector: 'posts',
        providers: [provide(PostsServiceToken, {useClass: PostsServiceImpl})]
    })
    export class Posts {
        private postsServices: PostsService;
    
        constructor(
            @Inject(PostsServiceToken)
            postsService: PostsService
            ) {
            console.log('Loading the Posts component');
            this.postsServices = postsService;
            ...
        }
    
        ...
    }    
    
    0 讨论(0)
  • 2021-01-05 05:58

    In typescript you can implement classes.

    Example

    config.service.ts:

    export class ConfigService {
      HUB_URL: string;
    }
    
    export class ConfigServiceImpl implements ConfigService {
      public HUB_URL = 'hub.domain.com';
    }
    
    export class ConfigServiceImpl2 implements ConfigService {
      public HUB_URL = 'hub2.domain.com';
    }
    

    app.component.ts:

    import { Component } from '@angular/core';
    import { ConfigService, ConfigServiceImpl, ConfigServiceImpl2 } from './config.service';
    
    @Component({
      ...
      providers: [
        { provide: ConfigService, useClass: ConfigServiceImpl }
        //{ provide: ConfigService, useClass: ConfigServiceImpl2 }
      ]
    })
    export class AppComponent {
    }
    

    You can then provide the service with different implementations.

    0 讨论(0)
  • 2021-01-05 06:02

    Any practical ideas how I can use interface based programming w/ TypeScript & Angular 2

    Interfaces are erased at runtime. In fact decorators don't support interfaces either. So you are better off using something that does exist at runtime (i.e. implementations).

    0 讨论(0)
  • 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 :

    /// <reference path="../../../../../_reference.ts" />
    
    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.

    0 讨论(0)
提交回复
热议问题