Jam*_*mes 5 typescript angular-material angular
我正在尝试订阅服务内的可观察对象。但是,我需要用于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();
}
}Run Code Online (Sandbox Code Playgroud)
AlertService 成为了一个Mat Snackbaron 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' });
}
}
});
}
}Run Code Online (Sandbox Code Playgroud)
我可以像这样订阅内部组件:
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);
}
}Run Code Online (Sandbox Code Playgroud)
然而,我正在尝试订阅内部服务,因为EmailService将在多个组件中使用。我怎样才能实现这种行为?
您的服务可以注入其他服务中
@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););
}
}
Run Code Online (Sandbox Code Playgroud)
如果AlertService使用EmailService并且EmailService使用AlertService,那就是循环了
| 归档时间: |
|
| 查看次数: |
3689 次 |
| 最近记录: |