次のように定義されたアラート ディレクティブがあります。
import { Component } from 'angular2/core';
import { CORE_DIRECTIVES } from 'angular2/common';
import { Alert } from 'ng2-bootstrap/ng2-bootstrap';
@Component({
  selector: 'alert_directive',
  templateUrl: './shared/directives/alert/alert.html',
  directives: [Alert, CORE_DIRECTIVES]
})
export class AlertDirective {
  alerts:Array<Object> = [ ];
  closeAlert(i:number) {
    this.alerts.splice(i, 1);
  }
  addAlert(message: string, style: string) {
    this.alerts.push({msg: message, type: style, closable: true});
    console.log(this.alerts);
  }
}
app次に、このディレクティブを含むコンポーネントを定義します。
import {AlertDirective} from '../../shared/directives/alert/alert';
...
@Component({
  selector: 'app',
  templateUrl: './app/components/app.html',
  styleUrls: ['./app/components/app.css'],
  providers: [UserService, HTTP_PROVIDERS],
  encapsulation: ViewEncapsulation.None,
  directives: [ROUTER_DIRECTIVES, AlertDirective]
})
...
これはすべて機能し、app.htmlファイルに関連する DOM にディレクティブが表示されます。
このapp.htmlファイルには、いくつかのグローバル html (navbar、footer、alert_directive) が含まれています。各ビューにディレクティブを追加しなくてもalert_directive、配列を変更して任意のビューからアラート メッセージを表示できるシングルトンになりたいと考えています。alerts
したがって、別のsign inコンポーネントでは:
import {Component, ViewEncapsulation} from 'angular2/core';
import {AlertDirective} from '../../shared/directives/alert/alert';
@Component({
  selector: 'sign_in',
  templateUrl: './sign_in/components/sign_in.html',
  styleUrls: ['./sign_in/components/sign_in.css'],
  encapsulation: ViewEncapsulation.Emulated
})
export class SignInCmp {
  alertDirective: AlertDirective;
  constructor(alertDirective: AlertDirective) {
    this.alertDirective = alertDirective;
  }
  showAlert() {
    this.alertDirective.addAlert('test', 'warning');
  }
}
ここでの問題はnewing、の新しいインスタンスを作成しているAlertDirectiveため、コンポーネントaddAlertで定義されている既存のインスタンスではなく、新しいインスタンスの配列にメソッドが追加されていることです。app
ディレクティブをシングルトンとして作成し、単一のインスタンスを各ビューに挿入するにはどうすればよいですか?そこで、そのシングルトンで任意のメソッドを呼び出して、注入された各インスタンスに影響を与えることができます。