我正在尝试订阅一个服务中的观察者。但是,我需要使用AlertService
来显示错误。一个服务在另一个服务中(循环依赖?)。
这是AlertService
@Injectable()
export class AlertService {
private subject = new Subject<any>();
private keepAfterNavigationChange = false;
constructor(private router: Router) {
// clear alert message on route change
router.events.subscribe(event => {
if (event instanceof NavigationStart) {
if (this.keepAfterNavigationChange) {
// only keep for a single location change
this.keepAfterNavigationChange = false;
} else {
// clear alert
this.subject.next();
}
}
});
}
success(message: string, keepAfterNavigationChange = false) {
this.keepAfterNavigationChange = keepAfterNavigationChange;
this.subject.next({ type: 'success', text: message });
}
error(message: string, keepAfterNavigationChange = false) {
this.keepAfterNavigationChange = keepAfterNavigationChange;
this.subject.next({ type: 'error', text: message });
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
AlertService成为AlertComponent
上的Mat Snackbar
。我要在另一个组件上渲染这个快餐栏。
export class AlertComponent implements OnInit {
message: any;
constructor(private alertService: AlertService, public snackBar: MatSnackBar) { }
ngOnInit() {
// trigger Snackbar after AlertService is called
this.alertService.getMessage().subscribe(message => {
if (message != null) {
// there is a message to show, so change snackbar style to match the message type
if (message.type === 'error') {
this.snackBar.open(message.text, undefined, { duration: 8000, verticalPosition: 'bottom', panelClass: ['snackbar-error'] });
} else if (message.type === 'success') {
this.snackBar.open(message.text, undefined, { duration: 8000, verticalPosition: 'bottom', panelClass: ['snackbar-success'] });
} else {
this.snackBar.open(message.text, undefined, { duration: 8000, verticalPosition: 'bottom' });
}
}
});
}
}
我可以像这样订阅内部组件:
export class AboutComponent implements OnInit {
ngOnInit() {
this.emailService.sendEmail('example@gmail.com')
.subscribe(code => {
console.log(code);
this.alertService.success('Thanks for your message!');
}, error => {
this.alertService.error('Error sending message.');
}
);
}
}
@Injectable()
export class EmailService {
constructor(private http: HttpClient) { }
sendEmail(email: Email) {
return this.http.post(BACKEND_URL + 'send', email);
}
}
但是,我尝试在服务内部订阅,因为EmailService
将在多个组件中使用。如何实现此行为?
发布于 2018-08-27 14:29:46
您的服务可以注入到其他服务中
@Injectable()export class EmailService {
constructor(private http: HttpClient, private alertService: AlertService) { }
sendEmail(email: Email) {
return this.http.post(BACKEND_URL + 'send', email).map( result => this.alertService.alert(result););
}
}
如果AlertService使用EmailService,而EmailService使用AlertService,那么它将是循环的
https://stackoverflow.com/questions/52041168
复制相似问题