我有一个警报服务,可将工作组件与显示弹出窗口的警报组件进行通讯。
我像这样EventEmitters
来工作:
alert.service.ts
export class AlertService {
@Output() alert: EventEmitter<any> = new EventEmitter()
sendAlertCont(data: any) {
this.getAlert.emit(data)
}
}
因此,在任何组件中,我都调用服务功能来激活警报组件
any.component.ts
export class AnyComponent {
constructor(private _alert: AlertService){}
clickedFunction(){
this._alert.sendAlertCont('You don't have permissions')
}
alert.component.ts
export class AlertComponent implements OnInit {
constructor(private _alert: AlertService){}
ngOnInit(){
this._alert.alert.subscribe(data => {
this.alerta = data
$('app-alert').fadeToggle()
})
}
问题是:
如何执行名为sendAlertCont()
的服务函数,在data
中返回响应sendig选项,并在发送警报的组件中获取响应:
AnyComponent :发送数据=> AlertService :活动警报=> AlertComponent :显示警报和选项
然后
AlertComponent :发送响应=> AlertService :获取并发送响应=> AnyComponent :接收响应
,但所有功能都相同。可以吗?
我在想一个像可观察的,Promise o异步函数之类的东西:
this._alert.sendAlertCont('You don't have permissions').then(...)
var res = await this._alert.sendAlertCont('You don't have permissions')
this._alert.sendAlertCont('You don't have permissions').suscribe(...)
答案 0 :(得分:2)
您可以这样做:
alert.service.ts
export class AlertService {
showAlert$ = new Subject<string>();
responeAlert$ = new Subject<string>();
alert(alert: string): Observable<any> {
this.showAlert$.next(alert);
return this.responeAlert$;
}
}
any.component.ts
export class AnyComponent {
constructor(private alertService: AlertService) { }
alert(): void {
this.alertService.alert('You don\'t have permissions').subscribe((result) => {
this.alertResult = result;
});
}
}
alert.component.ts
export class AlertComponent implements OnInit {
constructor(private alertService: AlertService) { }
ngOnInit() {
this.alertService.showAlert$.subscribe(alert => {
// code for displaying this component
})
}
close(result: string): void {
this.alertService.responeAlert$.next(result);
}
}
答案 1 :(得分:1)
我喜欢使用BehaviorSubject
在组件和服务之间进行通信。您的AlertService
可能是这样的:
alert = new BehaviorSubject<string>("");
alertResponse = new BehaviorSubject<string>("");
sendAlert(message: string) {
this.alert.next(message);
}
sendResponse(message: string) {
this.alertResponse.next(message);
}
然后在AnyComponent
中,您可以发送警报:
sendAlert() {
this.alertService.sendAlert("You don't have permissions.");
}
在AlertComponent
中显示警报消息并等待用户确认:
alertMessage: string;
constructor(private alertService: AlertService) {
this.alertService.alert.subscribe(res => this.alertMessage = res);
}
reply(message: string) {
this.alertService.sendResponse(message);
}
然后在AnyComponent
中再次订阅并显示来自AlertComponent的用户响应:
alertResponse: string;
constructor(private alertService: AlertService) {
this.alertService.alertResponse.subscribe(res => this.alertResponse = res);
}
根据您的要求检查我进行的Stackblitz:https://stackblitz.com/edit/angular-opqhj4