2017-07-16 64 views
3

警报服务消息正在调用,但警报未显示。 我正在使用角度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> 

回答

1

实际上你需要添加AlertComponent的地方,如果你想显示它。尝试在app.component.html文件中添加<alert></alert>以上<router-outlet></router-outlet>