Angular 从服务到组件的数据
Angular data from service to component
这是我的 code.it 是一个简单的服务。我如何在确认点击后发送数据结果到相关组件。如果我确认点击数据结果=真否则假。我必须看到这个数据结果在组件文件中
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')
}
})
}
}
由于单击对话框中的 accept/deny 按钮是一个异步操作,您可以 return 此函数对 return 数据的承诺:
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
});
});
}
与组件相比,当调用服务函数时,您可以从 promises 回调中接收数据:
yourComponent.confirm().then(
(yourDataSuccess) => {
// do something
},
(yourDataDenied) => {
// do something
},
)
这是我的 code.it 是一个简单的服务。我如何在确认点击后发送数据结果到相关组件。如果我确认点击数据结果=真否则假。我必须看到这个数据结果在组件文件中
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')
}
})
}
}
由于单击对话框中的 accept/deny 按钮是一个异步操作,您可以 return 此函数对 return 数据的承诺:
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
});
});
}
与组件相比,当调用服务函数时,您可以从 promises 回调中接收数据:
yourComponent.confirm().then(
(yourDataSuccess) => {
// do something
},
(yourDataDenied) => {
// do something
},
)