2017-07-16 3 views
3

アラートサービスメッセージが呼び出されてもアラートが表示されません。 私は角度2のフレームワークを使用しています。角度2でアラートサービスが機能していません

以下のように警告コードを追加しました。

アラート.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内部のアラートサービスを呼んでいます。あなたはそれを表示したい場合は、実際にあなたのAlertComponentどこかを追加する必要が

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

答えて

1

alert.html

####import ###### 
import { AlertService } from './alert.service'; 
#######component######## 
, 
    providers: [AlertService] 
########constructor### 
, 
    private alertService: AlertService 

this.alertService.success("value has been deleted for", true); 

app.component.htmlファイルの内側にの上に<router-outlet></router-outlet>を追加してください。

関連する問題