I've wrote a few services to function as standalone services, i.e. doing some fetching and scraping, then calling some other repository services to save to DB. Point being: the service is not instantiated by a controller, just trying to instantiate in Server.ts.
Cannot inject service into Server.ts. Can compile without error, but the instance of the service class comes back as undefined.
Services directory// ShopifyScraperService.ts
import { Service } from '@tsed/common'
import { AbstractScraperService } from './AbstractScraperService'
@Service()
export class ShopifyScraperService extends AbstractScraperService {
public startScraping = (url: string) => {
console.log('hey, welcome to scraper service')
}
}
Server.ts and try to call class method// Server.ts
import { GlobalAcceptMimesMiddleware, InjectorService, ServerLoader, ServerSettings } from '@tsed/common'
import '@tsed/mongoose'
import '@tsed/multipartfiles'
import { ShopifyScraperService } from './services/scraping/ShopifyScraperService'
// config @serversettings here
export class Server extends ServerLoader {
public $onReady() {
const shopifyScraperService: ShopifyScraperService = InjectorService.get(ShopifyScraperService)
console.log(shopifyScraperService) // <--- WILL PRINT UNDEFINED
shopifyScraperService.startScraping('https://scrapme.com/stuff') // <-- WILL THROW ERROR
}
}
@Inject decorator above $onReady hook. Like: @Inject()
$onReady(service: Service) {
// service.doSomething()
}
Server class, like: export class Server extends ServerLoader {
constructor(public shopifyScraperService: ShopifyScraperService){}
InjectorService. See code sample from steps to reproducesetTimeoutThanks in advance!
you can grab the instance of your service like this:
export class Server extends ServerLoader {
public $onReady() {
const shopifyScraperService: ShopifyScraperService = this.injector.get(ShopifyScraperService)
shopifyScraperService.startScraping('https://scrapme.com/stuff')
}
}
Solution from @milewski worked completely
Thanks!
Most helpful comment
you can grab the instance of your service like this: