我正在尝试在服务中订阅一个可观察对象。但是,我需要使用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在Mat Snackbar
上成为了AlertComponent
。我正在将此快餐栏渲染到另一个组件上。
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
将在多个组件中使用。我该如何实现这种行为?
答案 0 :(得分:0)
您的服务可以注入其他服务
@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,那将是循环的