从服务到组件的Angular数据



这是我的代码。这是一个简单的服务。如何在确认点击相关组件后发送数据结果。如果你确认点击数据结果=真否则假。你必须在组件文件

中看到这个数据结果。
import { Injectable } from '@angular/core';
import Swal from 'sweetalert2';
@Injectable({
providedIn: 'root',
})
export class SweetalertService {
constructor() {}

confirm(){
Swal.fire({
title: 'Do you want to save the changes?',
showDenyButton: true,
showCancelButton: true,
confirmButtonText: 'Save',
denyButtonText: `Don't save`,
}).then((result) => {

if (result.isConfirmed) {
Swal.fire('Saved!', '', 'success')
} else if (result.isDenied) {
Swal.fire('Changes are not saved', '', 'info')
}
})

}
}

由于单击对话框中的接受/拒绝按钮是异步操作,因此可以在此函数上返回一个承诺以返回数据:

confirm() {
return new Promise<YourResponseType>((resolve, reject) => {
Swal.fire({
title: 'Do you want to save the changes?',
showDenyButton: true,
showCancelButton: true,
confirmButtonText: 'Save',
denyButtonText: `Don't save`,
}).then(result => {
if (result.isConfirmed) {
Swal.fire('Saved!', '', 'success');
resolve(yourDataSuccess);
return;
}
if (result.isDenied) {
Swal.fire('Changes are not saved', '', 'info');
reject(yourDataDenied);
return;
}
reject(yourDataDefault); // this is an "otherwise" return, to catch possible other paths from this dialog business rules. Might not be necessary
});
});
}

从组件中,当调用服务函数时,你可以从承诺回调中接收数据:

yourComponent.confirm().then(
(yourDataSuccess) =>  {
// do something
},
(yourDataDenied) =>  {
// do something
},
)

相关内容

  • 没有找到相关文章

最新更新