Reputation: 3102
I´m trying to create a CRUD in Angular. Aparently the CRUD works but i want to improve code so i need avoid some sweetalert code to use only once. I think I can create a service and create different functions, like this
export ModalClass{
showconfirmdialog(title, text, icon){
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this imaginary file!",
icon: "warning",
buttons: true,
})
.then((willDelete) => {
if (willDelete) {
swal("Poof! Your imaginary file has been deleted!", {
icon: "success",
});
} else {
swal("Your imaginary file is safe!");
}
});
}
}
Then in .ts file inject this class and functions like this
import {ModalClass} from 'blabla'
deletefunction(){
this.http.get('API').subscribe()
this.ModalClass.showconfirmdialog('Was deleted','all ok', 'fa-ok')
}
Nothing happens. I debug response and return something like
[Object Object]
So the question is : How can i create a service with reutilizable code and inject this in ts files?
Upvotes: 0
Views: 8272
Reputation: 10264
You don't need to create you own service, there are a few packages that do it for you.
The best IMO is the official package: @sweetalert2/ngx-sweetalert2.
1 - Install it:
npm install --save sweetalert2 @sweetalert2/ngx-sweetalert2
2 - Import the module:
import { SweetAlert2Module } from '@sweetalert2/ngx-sweetalert2';
@NgModule({
//=> Basic usage (forRoot can also take options, see details below)
imports: [SweetAlert2Module.forRoot()],
//=> In submodules only:
imports: [SweetAlert2Module],
//=> In submodules only, overriding options from your root module:
imports: [SweetAlert2Module.forChild({ /* options */ })]
})
export class AppModule {
}
3 - Use it.
See the documentation here
Additional answer:
Of course that you can develop your own service, but you will need to wrap all your calls within NgZone.run() and take care of a lot of problems that will appear to you, create a buggy service that will give you a lot of headaches.
Trust me, I did this with a lot of libraries in the beginning of Angular 2+, when there hasn't packages like this.
Upvotes: 2