Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can my service extends an abstract class? Should my abstract class be @Injectable?

I have the following code:

import { Injectable } from "@angular/core";

@Injectable()
export abstract class ClientCacheService {
    private subscriptionId: string;
    protected getId(key :string, prefix:string=""): string {
        return `${this.subscriptionId}_${prefix}_${key}`;
    }

    constructor(subscriptionId: string) {
        this.subscriptionId = subscriptionId;
    }

    abstract setCache(key :string, prefix:string, object: any): void;
    abstract getCache(key :string, prefix:string): void;
    abstract removeCache(key :string, prefix:string): any;
}


import { ClientCacheService } from "./client-cache.service";
import { Injectable } from "@angular/core";

@Injectable()
export class SessionCacheService extends ClientCacheService {
    constructor() {
        super("TEST");
    }
    setCache(key: string, prefix: string, object: any): void {
        window.sessionStorage.setItem(this.getId(key, prefix), JSON.stringify(object));
    }    
    getCache(key: string, prefix: string): void | null {
        let res = window.sessionStorage.getItem(this.getId(key, prefix));
        return res ? JSON.parse(res) : null;
    }
    removeCache(key: string, prefix: string) {
        window.sessionStorage.removeItem(this.getId(key, prefix));
    }
}

I'm getting the following error when I compile in production mode (ng build --prod --output-hashing none --aot false):

Can't resolve all parameters for e

I have two question about this code:

  • Can my SessionCacheService extends a Abstract class?
  • This abstract class should be @Injectable() or not?
like image 314
Ricardo Rocha Avatar asked Oct 25 '25 22:10

Ricardo Rocha


1 Answers

  1. Yes, your concrete implementation of service class can extend abstract class
  2. No, base class does not need to (in fact it should not to be) annotated

Regarding point 2, just consider what @Injectable means to Angular? It's a sign for hierarchical injector, that this class can be injected into other class via dependency injections. What is injected? Class instance. Can abstract classes be instantiated? Not really :)

Issue you are getting while building for --prod is related with dead code elimination and tree shaking I suppose, where all @Injectable instances are reference-traced to check if they are really needed in any hierarchical call.

like image 191
Tomas Avatar answered Oct 27 '25 11:10

Tomas