我的服务可以扩展抽象类吗?我的抽象类应该是 @Injectable 吗?

Ric*_*cha 4 typescript angular

我有以下代码:

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

在生产模式下编译时出现以下错误 ( ng build --prod --output-hashing none --aot false):

无法解析 e 的所有参数

我对这段代码有两个问题:

  • 我可以SessionCacheService扩展抽象类吗?
  • 这个抽象类应该是@Injectable()还是不是?

Tom*_*mas 7

  1. 是的,服务类的具体实现可以extend 抽象类
  2. 不,基类不需要(实际上不应该)注释

关于第2点,只要考虑@InjectableAngular意味着什么?这是分层注入器的标志,该类可以通过依赖注入注入到其他类中。注射的是什么?类实例。抽象类可以实例化吗?并不真地 :)

--prod我认为您在构建时遇到的问题与死代码消除和树摇动有关,其中所有@Injectable实例都被引用跟踪以检查它们在任何分层调用中是否确实需要。