How to write a plugin for API services in Nxt?

I want to write a plugin that contain all needed services and use this services easily when is needed. I have wrote a plugin but it doesn’t work !! How to know what is wrong ? This is plugin i wrote .

export default ({ $axios}:any , inject:any) => {

    class BlogService {

        getPost() {
            return $axios.$get('/posts')
        }
        
        delete(id: Number) {
            return $axios.Sdelete('/post/' + id)
        }

    }
    inject(new BlogService)
}

And this is error i get enter image description here

Answer

The inject method takes in two parameters. The first parameter is a string and will be the name of the property and then the second argument is the value (in your case, new BlogService()). I would also add the value to the context, so that you can access your service in asyncData and anywhere else the context is available.

Here’s a rewritten version of your snippet, with these changes applied:

export default (context, inject) => {
    const { $axios } = context

    class BlogService {

        getPost() {
            return $axios.$get('/posts')
        }
        
        delete(id) {
            return $axios.Sdelete('/post/' + id)
        }

    }
    
    const blogService = new BlogService()

    context.$blogService = blogService // Adds $blogService to the context.
    inject('blogService', blogService) // Adds $blogService to all of your components.
}

While you haven’t tagged your post with TypeScript, it looks as if you’re using TypeScript in your original snippet, so I’ve also rewritten the snippet for TypeScript as you’ll need to extend the default types with your new injected property. This is just to stop your linter from going crazy and your code completion to work.

import { Context, Plugin } from '@nuxt/types'

class BlogService {
    readonly context: Context

    constructor (context: Context) {
        this.context = context
    }

    getPost() {
        return this.context.$axios.$get('/posts')
    }

    delete(id: number) {
        return this.context.$axios.Sdelete('/post/' + id)
    }
}

// Create a new interface so that you don't have to add the new properties to all of the existing types every time.
interface Services {
  $blogService: BlogService
}

declare module 'vue/types/vue' {
  interface Vue extends Services {
  }
}

declare module '@nuxt/types' {
  interface NuxtAppOptions extends Services {
  }

  interface Context extends Services {
  }
}

const servicesPlugin: Plugin = (context, inject) => {
    const { $axios } = context
    
    const blogService = new BlogService(context)

    context.$blogService = blogService // Adds $blogService to the context.
    inject('blogService', blogService) // Adds $blogService to all of your components.
}

export default servicesPlugin