Instead of creating a new instance of ToastService
in your function, it is advisable to avoid that approach to retain all the benefits of DI.
You could consider the following alternative approach:
export function copy(str:string){
// set clipBoard...
const toastService = new ToastService();
toastService.success('copied!');
}
It is recommended to either convert your utils
into a service, as suggested by others (which is the optimal solution), or extract common code into another function (if feasible) and utilize it in both instances. This could be implemented as follows:
shared.utils.ts:
export function toastSuccess(message: string) {
// your logic
}
toast.service.ts
import {toastSuccess} from './shared.utils';
@Injectable({providedIn: 'root'})
export class ToastService {
success(message: string) {
toastSuccess(message);
}
}
utils.ts
import {toastSuccess} from './shared.utils';
export function copy(str:string){
// set clipBoard...
toastSuccess('copied!');
}