简体   繁体   中英

NestJs Dependency injection get multiple instance in a single class

I have a class Item below

@Injectable()
export class Item {
   name: string;
}

I am injecting Item class into ItemService

export class ItemService {
    constructor(private readonly item: Item) {}
    
    save(items) {
        items.forEach((data) => {
            this.item.name = data.name;
            this.item.save();
        });
    }
}

The problem here is I am not getting new instance of item for every loop. How can I achieve this with dependency injection in nestjs.

I am not getting new instance of item for every loop. Blockquote

That's what dependency injection is, you inject the already created object of class if available, It follows the singleton pattern.

How can I achieve this with dependency injection in nestjs.

By creating a new object in each iteration;

import item from 'Item'

export class ItemService {
    constructor() {}
    
    save(items) {
        items.forEach((data) => { 
            item = new Item()
            item.name = data.name;
            item.save();
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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