Alert service not working in angular 2
Alert message triggers a call, but no alert is displayed. I am using angular 2 framework.
I have added a warning code as shown below.
Alert.ts file.
import { Component, OnInit } from '@angular/core';
import { AlertService } from './alert.service';
@Component({
selector: 'alert',
templateUrl: 'alert.html'
})
export class AlertComponent {
message: any;
constructor(private alertService: AlertService) { }
ngOnInit() {
console.log("Calling init function");
this.alertService.getMessage().subscribe(message => { this.message = message; });
}
}
alert.service.ts
import { Injectable } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';
@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;
console.log("Calling alert services");
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();
}
}
app.component.ts and I am calling alert services inside app.component.ts like this.
####import ######
import { AlertService } from './alert.service';
#######component########
,
providers: [AlertService]
########constructor###
,
private alertService: AlertService
this.alertService.success("value has been deleted for", true);
alert.html
<div *ngIf="message" [ngClass]="{ 'alert': message, 'alert-success': message.type === 'success', 'alert-danger': message.type === 'error' }">{{message.text}}</div>
+3
source to share