簡體   English   中英

從服務到組件的角度數據

[英]Angular data from service to component

這是我的代碼。這是一個簡單的服務。如何在確認點擊相關組件后發送到數據結果。如果我確認點擊數據結果=true,否則為 false。必須在組件文件中查看此數據結果

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')
      }
    })


  }
}

由於單擊對話框中的接受/拒絕按鈕是異步操作,因此您可以在此函數上返回一個 Promise 以返回數據:

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
        });
    });
}

與組件相比,調用服務函數時,您可以從 Promise 回調中接收數據:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM