Angular 9.0.5项目构建时swal.noop触发废弃警告的重构方案及疑问咨询
swal is deprecated Warning in Angular 9 First off, yes—this is a real, valid warning. SweetAlert2 deprecated the legacy promise rejection behavior (where dismissing an alert would reject the promise) in favor of a more promise-compliant approach where all alerts resolve with a result object, even when dismissed. Your use of swal.noop is tied to that old behavior, hence the warning.
Why This Happens
In older versions of SweetAlert2 (pre-v7, or when using the useRejections: true option), closing an alert without confirming would reject the promise. Developers used catch(swal.noop) to suppress unhandled rejection errors from these cases. However, the team changed this because promise rejections should be reserved for actual errors, not user actions like closing an alert.
How to Refactor Your Code
The fix involves two key steps:
Update your
errorPopupservice method (if you control it):
Remove theuseRejections: trueoption from theswal()call. This ensures the promise always resolves, even when the user dismisses the alert. For example:// In companyHelperService errorPopup(title: string, errorMessage: string) { return swal({ title: title, text: errorMessage, type: 'error', // Remove useRejections: true if present confirmButtonText: 'OK' }); }Adjust the component code to handle the resolved promise:
Since the promise no longer rejects, you can remove the.catch(swal.noop)entirely. If you need to react to the user's action (like clicking OK), use.then()to check the result:private promptFormError(title: string, errorMessage: string) { this.companyHelperService.errorPopup(title, errorMessage) .then(result => { // Optional: handle user actions if needed if (result.isConfirmed) { // User clicked the OK button console.log('Alert confirmed'); } else { // User dismissed the alert (escape, click outside, etc.) console.log('Alert dismissed'); } }); // No need for catch(swal.noop) anymore! }
If you don't need to react to the user's action at all, you can simplify it even further:
private promptFormError(title: string, errorMessage: string) { this.companyHelperService.errorPopup(title, errorMessage); }
Key Documentation Context (for SweetAlert2 7.22.2)
While I can't link directly to the docs, here's what you need to know from that version's documentation:
- The
useRejectionsoption was marked as deprecated in v7. - All alert promises now resolve with a
SweetAlertResultobject that includes:isConfirmed:trueif the user clicked the confirm buttonisDismissed:trueif the alert was closed via any other meansdismiss: A string like'escape','backdrop', or'cancel'indicating how the alert was dismissed
By making these changes, you'll eliminate the deprecation warning and align your code with SweetAlert2's modern, promise-friendly API.
内容的提问来源于stack exchange,提问作者Youri

