Angular Materials 没有内置的 Alert 组件,但你可以很容易地实现一个并对其进行自定义,该实现包括一个组件和一个服务,模板和 CSS 文件完成这些组合。
警报组件
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { AlertService } from 'src/app/_services';
@Component({
selector: 'alert',
templateUrl: 'alert.component.html',
styleUrls: ['./alert.component.css']
})
export class AlertComponent implements OnInit, OnDestroy {
private subscription: Subscription;
message: any;
constructor(private alertService: AlertService) { }
ngOnInit() {
this.subscription = this.alertService.getMessage().subscribe(message => {
this.message = message;
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
警报模板
<div *ngIf="message" [ngClass]="{ 'alert': message, 'alert-success': message.type === 'success', 'alert-danger': message.type === 'error' }">{{message.text}}</div>
警报方式
.alert-danger {
background-color: #f44336; /* Red */
}
.alert-success {
background-color: #36f456;
}
.alert{
padding: 20px;
color: white;
margin-bottom: 15px;
text-align: center;
}
警报服务
import { Injectable } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { Observable, Subject } from 'rxjs';
@Injectable()
export class AlertService {
private subject = new Subject<any>();
private keepAfterNavigationChange = false;
constructor(private router: Router) {
// clear alert message on route change
this.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();
}
}
典型用途
this.alertService.error("Error!! Something went wrong");
this.alertService.success("Success, You are done");
登录失败时显示警报的用法示例
onSubmit(){
this.authService.login(this.user).subscribe(
(res: any) => {
if(!res.hasError && res.token){
this.authService.isLoggedIn = true;
localStorage.setItem('token', res.token);
this.router.navigate(['/']);
} else {
this.alertService.error(res.errorMessage);
}
},
err => {
this.alertService.error(err.errorMessage);
}
);
}