I'm not much in TypeScript and encounter an issue. The code looks as following:
1) Main.ts:
import gpbApi from '@/utils/api/gpbApi';
@Component
export default class ExtendedDetailAccountComponent extends mixins(CurrentUserMixin) {
...
async created() {
try {
console.log('gpbApi =', gpbApi);
const result = await gpbApi.leadService.getReqtypes();
console.log('result =', result);
} catch (error) {
console.log('error = ', error);
}
}
...
2) vue.d.ts:
import gpbApi from './utils/api/gpbApi';
declare module 'vue/types/vue' {
interface Vue {
$gpbApi: typeof gpbApi;
}
}
3) gpbApi.ts:
import leadService from '@/utils/api/leadService';
class GpbApi {
leadService!: typeof leadService;
}
const instance = new GpbApi();
export default instance;
4) leadService.ts:
import axios from 'axios';
const path = '...';
class LeadService {
async getReqtypes() {
const { data } = await axios.get(`${path}/Reqtype`, { withCredentials: true });
return data.data;
}
}
const instance = new LeadService();
export default instance;
I get an error:
leadService: undefined
error = TypeError: Cannot read properties of undefined (reading 'getReqtypes')
at VueComponent.created
How to get rid of this error?
CodePudding user response:
You basically never instantiate leadService field of GpbApi if I am see it correctly.
So, you should instantiate loadService
field in gpbApi
class GpbApi {
leadService = leadService;
}
CodePudding user response:
I would suggest removing typeof word from interface properties declaration like:
interface Vue {
$gpbApi: gpbApi;
}
and the same with class definition:
class GpbApi {
leadService!: leadService;
}