简体   繁体   English

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

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

I need to create a new instance with a generic type in angular5 service. 我需要在angular5服务中创建一个具有泛型类型的新实例。
Check out the following codes, please. 请检查以下代码。

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

But it's not working. 但这不起作用。 I've been trying to find a solution over a day but can't find it yet. 我已经尝试了一天的解决方案,但还找不到。

Thanks 谢谢

You're close the correct usage: 您正在关闭正确的用法:

@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;
    }
 }

Sample Class 样品分类

export class SampleClass {

    constructor() {
        // Some attributes
    }

}

And somewhere in a service or in a component you would call the duplicate method like this: 在服务或组件中的某处,您将调用duplicate方法,如下所示:

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

If you "don't know" the class of the object you can use a clone method of a library like lodash . 如果“不知道”对象的类,则可以使用诸如lodash之类的库的clone方法。

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

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