Edoardo Tarnoczy
Edoardo Tarnoczy

Reputation: 11

Use Vue3 inject inside a Typescript class

I'm creati an error reporting service, and trying to provide it for the entire app.

import ErrorReporter from "@/services/error_reporter/error-reporter.service";

const app = createApp(App);

app.provide('errorReporter', new ErrorReporter());

and the importing it in a Ts class like so

import {inject} from "vue";

export default class OAuthFedIdService {

    errorReporter: ErrorReporter = inject("errorReporter") as ErrorReporter;

but i get this warning inside the console

inject() can only be used inside setup() or functional components.

is there a way to use the provide/inject functionality of Vue outside of components without getting warnings?

Upvotes: 1

Views: 1287

Answers (1)

Michal Levý
Michal Levý

Reputation: 37753

No, there is no way to use the provide/inject outside of components

Just create and export singleton instance of your service. Use inject in components and use direct import anywhere else...

Upvotes: 1

Related Questions