通用化Angular服务以提供共享通用逻辑的许多不相关服务实现

时间:2019-07-02 12:33:05

标签: angular

我正在寻找一种Angular方式来创建5-10个功能无关的服务,其中所有这些服务共享90%的逻辑处理对底层API功能的访问。目前我有这样的事情:

@Injectable({providedIn: 'root'})
export class FeatureServiceFactory {
    serviceMap: {
        [key: ApiFeature]: FeatureService
    } = {};

    constructor(private dependency1: Dependency1,
                private dependency2: Dependency2,
                private dependency3: Dependency3) {}

    provideFeatureService(key: ApiFeature) {
        if(!this.serviceMap[key]) {
            this.serviceMap[key] = new FeatureService(key, this.dependency1, this.dependency2, this.dependency3);
        }
        return this.serviceMap[key];
    }
}

export class FeatureService {
    constructor(private key: ApiFeature,
                private dependency1: Dependency1,
                private dependency2: Dependency2,
                private dependency3: Dependency3) {}
    // some common API related logic and methods here
}

enum ApiFeature {
    Bluetooth = 'Bluetooth',
    Location = 'Location',
    NFC = 'NFC',
    RemoteNotifications = 'RemoteNotifications'
    Wifi = 'Wifi',
    // some 5 more to follow
}

上面的逻辑通常会起作用(一件事是,对于某些2种特定情况,我可能需要与ApiFeature一起添加一些额外的访问器逻辑)。 由于使用特定的FeatureService实例是独立的问题,因此想知道上述方法是否可以通过“工厂”服务间接请求实际的服务实例,或者是否有其他Angular方式可以实现。

0 个答案:

没有答案