繁体   English   中英

如何在angular5服务中创建具有泛型类型的新实例

[英]How to create a new instance with generic type in angular5 service

我需要在angular5服务中创建一个具有泛型类型的新实例。
请检查以下代码。

@Injectable()
export class LookupService {
  duplicate<T>(lookup: T) {
    const temp = new T(lookup);
    return temp;
  }
}

但这不起作用。 我已经尝试了一天的解决方案,但还找不到。

谢谢

您正在关闭正确的用法:

@Injectable()
export class LookupService {
    // You need also a reference to the class to create a new object
    duplicate<T>(lookup: T, clazz: { new(): T }) {
        const temp = new clazz();
        // Set some values of lookup to temp
        return temp;
    }
 }

样品分类

export class SampleClass {

    constructor() {
        // Some attributes
    }

}

在服务或组件中的某处,您将调用duplicate方法,如下所示:

const obj: SampleClass = new SampleClass();
// Call the method with the object to clone and its class
this.lookupService.duplicate(obj, SampleClass);

如果“不知道”对象的类,则可以使用诸如lodash之类的库的clone方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM