簡體   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