警报服务在角度2中不起作用

警报服务消息正在被调用,但警报未显示.

我正在使用角度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; });
            }
        }

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
我正在调用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);

alert.html

<div *ngIf="message" [ngClass]="{ 'alert': message, 'alert-success': message.type === 'success', 'alert-danger': message.type === 'error' }">{{message.text}}</div>

最佳答案 如果要显示它,您需要在某处实际添加AlertComponent.尝试添加< alert>< / alert>以上< router-outlet>< / router-outlet>在app.component.html文件中.

点赞