Ricardo Rocha
Ricardo Rocha

Reputation: 16266

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:

Upvotes: 4

Views: 2289

Answers (1)

Tomas
Tomas

Reputation: 3436

  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.

Upvotes: 7

Related Questions