在 Angular 5 中保留 class 的实例

Preserve instance of class in Angular 5

真的可以这样做吗?

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

@Injectable()
export class UbiSharedService {

    private _ubiData: object = {};

    private $$instance: UbiSharedService;

    constructor() {

    }

    public setData(key: string, data: any) {
        this._ubiData[key] = data;
    }

    public getData(key: string): any {
        return this._ubiData[key];
    }

    public popData(key: string): any {
        return delete this._ubiData[key];
    }

    public getInstance(): UbiSharedService {
        if (!!this.$$instance && this.$$instance instanceof UbiSharedService) {
            //NOOP
        }
        else {
            this.$$instance = new UbiSharedService();
        }

        return this.$$instance;
    }


}

摆脱 $$instance,而是使用构造函数将服务注入到需要它的组件中。

constructor(private productService: ProductService,
                private productParameterService: ProductParameterService) { }

然后组件可以使用 productServiceproductParameterService 属性访问服务方法。

请参阅 Angular 中的以下文档,了解如何使用服务在不相关的组件之间共享数据: https://angular.io/guide/singleton-services.

您可以通过将服务添加到组件的构造函数来在组件中注入服务:

constructor(
    private ubiSharedService: UbiSharedService
) { 
   // You can now call in the methods of ubiSharedService
   // e.g.: this.ubiSharedService.setData('key', { value: 'Value' });
}