How to use sweetalert2 preConfirm with httpRequest which needs to be subscribed to within Angular 9 component - angular9

I have an Angular form component which sends a http request and subscribes to that request. Now I'm trying to add a sweetalert2 feature to start a loader when the form is submitted (onSubmit()) and the http request is executed (with doSubmit()) and I'd like the sweetalert modal to change to a success or error message when http request returns a response which is subscribed to by the component (resulting in execution of onSuccess() or onError()). For some reason, my swal.preConfirm doesn't change the sweetalert from the loader to a success or error message. Can you please help?
protected doSubmit(): Observable<NewUser> {
swal.queue([{
title: 'Registration',
text: 'Processing your information',
onBeforeOpen: () => {
swal.showLoading()
},
preConfirm: () => {
return this.onSuccess()
.then(() =>
swal.insertQueueStep({
title: 'Success'
})
)
.catch(() =>
swal.insertQueueStep({
title: 'Error'
})
)
}
}])
return this.httpService.callDatabase<NewUser>('post', '/api/users/register', this.value)
}
onSubmit() {
if (this.form.valid) {
this.doSubmit().subscribe(
() => {
this.error = null;
this.onSuccess();
},
err => {
this.error = err
this.onError();
},
() => {
this.submitted = false;
this.completed = true;
}
)
}
}
onSuccess(){
return new Promise((resolve){
resolve('success')
})
onError(){
return new Promise((reject){
reject('error')
})

I figured out a bit of a make shift solution for this issue without using swal.preConfirm. Hopefully, there is a more elegant solution to achieving the same. For now, here's my solution:
protected doSubmit(): Observable<NewUser> {
this.invalidOnError = '';
this.navigationExtras = { queryParams: this.asssignToNavExtras.assignToNavExtras({ username: this.username.value }) };
swal.fire({
title: 'Registration',
text: 'Processing your information',
onBeforeOpen: () => {
swal.showLoading()
}
})
.then
return this.httpService.callDatabase<NewUser>('post', '/api/users/register', this.value)
};
onSubmit() {
if (this.form.valid) {
this.doSubmit().subscribe(
() => {
this.error = null;
this.onSuccess();
},
err => {
this.error = err
this.onError();
},
() => {
this.submitted = false;
this.completed = true;
}
)
}
}
protected onSuccess() {
swal.fire({
title: 'Registration Successful',
text: 'Thank you',
icon: 'success',
confirmButtonText: 'OK',
buttonsStyling: false,
customClass: {
confirmButton: 'btn'
},
timer: 10000,
})
}
protected onError() {
swal.fire({
showConfirmButton: false,
timer: 10,
onAfterClose: () => {
code for where to place focus after sweetalert is closed
}
})
}

Related

The GET method is not supported for route form2/submit. Supported methods: POST. Laravel 9 Vue js 3

I wanted to create a function to submit image and text to database through a form but I keep getting the error :
POST http://127.0.0.1:8000/form2/submit 500 (Internal Server Error)
this is my route :
Route::post('/form2/submit', [Form2Controller::class, 'store']);
The controller :
public function index()
{
return Form2::all();
}
public function store(Request $request)
{
$data = $request->all();
if ($request->hasFile('image')) {
$image = $request->file('image');
$path = $image->store('public/images');
$data['image'] = $path;
}
$response = Form2::create($data);
return response()->json([
'status' => 'success',
'data' => $response
], 200);
}
The form :
<Form #submit="saveData()" enctype="multipart/form-data">
<Field name="nomor"
type="text"
class="form-control3"
v-model="form2.nomor"
placeholder=" Nomor Telfon"
:rules="isRequired"
/>
<br>
<ErrorMessage name="nomor"/>
<br>
<Field name="image"
type="file"
class="form-control3"
v-model="form2.image"
/>
</Form>
The Script :
<script>
import axios from 'axios';
import { Form, Field, ErrorMessage} from 'vee-validate';
export default {
components: {
Form,
Field,
ErrorMessage
},
data() {
return {
form2: {
nama: '',
alamat: '',
nomor: '',
email: '',
image: '',
},
};
},
methods: {
isRequired(value){
if (value && value.trim()){
return true;
}
return 'This is required';
},
validateEmail(value) {
// if the field is empty
if (!value) {
return 'This field is required';
}
// if the field is not a valid email
const regex = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (!regex.test(value)) {
return 'This field must be a valid email';
}
// All is good
return true;
},
saveData(){
axios.post('/form2/submit', this.form2).then(
response => {
console.log(response);
this.$toast.success(`Data berhasil dikirim`,{
position: "bottom",
});
}
). catch(error => {
console.log('error');
this.$toast.error(`Terjadi kegagalan`,{
position: "bottom",
});
})
}
}
};
</script>
I tried adding method="POST" to the form but it still won't help, why am I getting this error when I'm not using any GET method?
Read this article about sending multipart/form-data using axios:
axios.post('/form2/submit', this.form2, {
headers: {
"Content-Type": "multipart/form-data",
},
})
Try preventing default behavior
saveData(e){
e.preventDefault()
}
Also you can't directly bind input file types:
This link helps you to handle
new Vue({
el: '#app',
data: {
image: ''
},
methods: {
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createImage(files[0]);
},
createImage(file) {
var image = new Image();
var reader = new FileReader();
var vm = this;
reader.onload = (e) => {
vm.image = e.target.result;
};
reader.readAsDataURL(file);
},
removeImage: function (e) {
this.image = '';
}
}
})

why my function is not working in another function in vue 3 axios in laravel?

I made this getData function to fetch the data from database, now I am calling this function in my add, update and delete function so I don't have too refresh every time after a click. Calling this function is working in the delete function but not in the add and update. Why?
I am trying to call the function the same way as I calling it in the delete function but it is not working for the add and update function
<script>
let App = ({
data() {
return {
add_numbertype: {
'id': null,
'name': null,
'character': null,
'created_by': null,
'updated_by': null,
'transaction_id': null,
'user': null,
'status': null
},
dataList: [],
};
},
created() {
this.getData();
},
methods: {
//function for fetching data
getData() {
axios.get('/data').then((response) => {
this.dataList = response.data.result;
})
},
//end
//function for adding data
addNumbertype() {
axios.post('/add', this.add_numbertype)
.then(function(response) {
if (response.status === 200) {
document.getElementById("add-form").reset();
$('#createModal').modal('hide');
Swal.fire(
'Add',
'New record added Successfully',
'success'
)
this.getData();
} else {
alert("error");
}
}).catch(function(error) {
console.log(error.response);
})
},
//end
//function for deleting data
deleteData(id) {
axios.get('/delete/' + id).then((response) => {
Swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
)
this.getData();
}).catch(function(error) {
console.log(error.response.data);
})
},
//end
//to show data in modal for update
editData(list) {
this.add_numbertype = {
'id_u': list.pn_id,
'name_u': list.pn_name,
'character_u': list.pn_character,
'updated_by_u': null,
'transaction_id_u': list.transactions_id,
'user_u': list.user,
'status_u': list.status
}
},
//end
//to update data
updateData(id) {
axios.post('/update/' + id, this.add_numbertype)
.then(function(response) {
if (response.status === 200) {
$('#updateModal').modal('hide');
document.getElementById("update-form").reset();
Swal.fire(
'Update',
'New record updated Successfully',
'success'
);
this.getData();
}
}).catch(function(error) {
console.log(error.response);
})
},
},
});
Vue.createApp(App).mount('#add');
</script>
The problem with the code in the addNumbertype method. In the .then function of the axios post request, this does not refer to the Vue component instance, but instead refers to the function scope. This means that this.getData will not work as expected and will result in a TypeError. To resolve this issue, you can use an arrow function instead to preserve the value of this. Here is the corrected code:
addNumbertype() {
axios.post('/add', this.add_numbertype)
.then((response) => {
if (response.status === 200) {
document.getElementById("add-form").reset();
$('#createModal').modal('hide');
Swal.fire(
'Add',
'New record added Successfully',
'success'
);
this.getData();
} else {
alert("error");
}
})
.catch((error) => {
console.log(error.response);
});
}
Additionally, there's also an issue in the updateData method where this also refers to the function scope and not the Vue component instance. The same solution can be applied here as well, use an arrow function to preserve the value of this. Here is the corrected code:
updateData(id) {
axios.post('/update/' + id, this.add_numbertype)
.then((response) => {
if (response.status === 200) {
$('#updateModal').modal('hide');
document.getElementById("update-form").reset();
Swal.fire(
'Update',
'New record updated Successfully',
'success'
);
this.getData();
}
})
.catch((error) => {
console.log(error.response);
});
}

show error message on duplicate data insertion in angular 14

`
saveDepartment(): void {
this.submitted = true;
if (this.deptForm.invalid) {
return
}
const data = {
Name: this.Department.name,
SortOrder: this.Department.sortOrder,
MaxStaff: this.Department.shortName,
IsActive: this.Department.isActive
};
this.DepartmentService.create(data)
.subscribe({
next: (res) => {
this.alert = true;
console.log(res);
},
error: (e) => console.error(e)
});
}
`
i need to show error message while inserting the duplicate data to the database

how to paginate ngx-datatable with http hearders?

I would like to centralize the pagination for all tables. perhaps with a service or a class.
my component:
getListaPalinsesti(){
this.filterCampain.filterSubject$.pipe(
tap(() => { this.loadingIndicator = true; }),
this.iListCampain.listCampain,
retry(2),
tap((e) => {
this.rows = e.body;
this.page.totalElements = Number(e.headers.get('x-total-count'))
}),
tap(() => { this.loadingIndicator = false; }),
catchError((error) => {
console.error('Error api', error);
this.loadingIndicator = false;
return EMPTY;
}),
takeUntil(this.unSubscribe$)
).subscribe()
}
my service:
listCampain: OperatorFunction<any, HttpResponse<any[]>> = switchMap((v) => this.controller.getList(v));
my controller(service)
public listCampain= (form: any, skip?:any, limit?:any, order_by?:any, desc?:any ): Observable<any> => { return this.http.post<HttpResponse<any[]>>(this.webApiBaseUrl + `list/_search?skip=${skip}`,form, {observe: 'response'}); }

What's the best way to mock a nested function?

consider a function
exports.projectNotifyLaunch = (admin, functions) => {
return functions.database.ref("/projects/{pid}").onCreate(snap => {
const { title } = snap.val();
const notification = {
title: `${title} just launched!`,
body: `We just heard about a new cryptocurrency project called ${title}`
};
return admin.messaging().sendToTopic("premium", { notification });
});
};
How should I mock deeply nested functions such as
functions.database.ref("/projects/{pid}").onCreate(snap => {});
or
admin.messaging().sendToTopic("premium", { notification });
in Jest? I want to fire off the snap=>{} callback and assert against the value of notification.
I was able to make this work
This works but it's quite verbose. I'm wondering if there is a better way, or a type of testing I'm not aware of with Jest.
describe("send notification to premium users on new project", () => {
// INPUTS
const snap = {
val: () => ({
title: "Test Title"
})
};
const functions = {
database: {
ref: () => ({
onCreate: callback => callback(snap)
})
}
};
// outputs
let topicStub = null;
let notificationStub = null;
const admin = {
messaging: () => ({
sendToTopic: (topic, notification) => {
topicStub = topic;
notificationStub = notification;
}
})
};
projectNotifyLaunch(admin, functions);
test("title is correct", () => {
expect(notificationStub.notification.title).toBe(
"Test Title just launched!"
);
});
test("topic is premium", () => {
expect(topicStub).toBe("premium");
});
});