kan*_*lal 5 alert modal-dialog angular
正在调用警报服务消息,但未显示警报。我正在使用 Angular 2 框架。
我添加了警报代码如下。
Alert.ts 文件。
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; });
}
}
Run Code Online (Sandbox Code Playgroud)
警报服务.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();
}
}
Run Code Online (Sandbox Code Playgroud)
app.component.ts 和我在 app.component.ts 内调用警报服务,如下所示。
####import ######
import { AlertService } from './alert.service';
#######component########
,
providers: [AlertService]
########constructor###
,
private alertService: AlertService
this.alertService.success("value has been deleted for", true);
Run Code Online (Sandbox Code Playgroud)
警报.html
<div *ngIf="message" [ngClass]="{ 'alert': message, 'alert-success': message.type === 'success', 'alert-danger': message.type === 'error' }">{{message.text}}</div>
Run Code Online (Sandbox Code Playgroud)
AlertComponent如果你想显示它,你需要实际添加你的地方。尝试将<alert></alert>上面的内容添加<router-outlet></router-outlet>到您的文件中app.component.html。
| 归档时间: |
|
| 查看次数: |
2303 次 |
| 最近记录: |