警报和导航栏 module/component/service:如何分离视图?

Alerts and navbar module/component/service: how to decouple views?

所以我以前在app.component.ts有这个功能:

addNewAlert() {
    this.appService.navbarPadding += 81;
    this.alertsService.alerts.push({
      type: 'info',
      msg: 'INFO'
    });
}

但它不属于那里。它属于服务吗? - 可能不是,服务应该与视图分离。 - 我可以将 alerts.component.ts 导入我的其他 Component 吗?

navbar.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { AppService } from '../app.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit, OnDestroy {
  navbarPadding: number;
  subNavbarPadding: Subscription;

  constructor(public appService: AppService) { }

  ngOnInit() {
    this.subNavbarPadding = this.appService.navbarPaddingChange.subscribe(val =>
      this.navbarPadding = val
    );
  }

  ngOnDestroy() {
    this.subNavbarPadding.unsubscribe();
  }
}

alerts.service.ts

import { Injectable } from '@angular/core';
import { IAlert } from './alert';

@Injectable()
export class AlertsService {
  public alerts: Array<IAlert> = [];

  public add(alert: IAlert): void {
    this.alerts.push(alert);
  }

  public close(i: number): void {
    this.alerts.splice(i, 1);
  }
}

alerts.component.ts

import { Component, Input, OnInit } from '@angular/core';
import { IAlert } from './alert';
import { AlertsService } from './alerts.service';
import { AlertComponent } from 'ng2-bootstrap';

@Component({
  selector: 'app-alerts',
  templateUrl: './alerts.component.html',
  providers: [AlertComponent],
  styleUrls: ['./alerts.component.css']
})
export class AlertsComponent implements OnInit {
  @Input() public type: string = 'warning';
  @Input() public dismissible: boolean;
  @Input() public dismissOnTimeout: number;

  public alerts: Array<IAlert>;

  constructor(private alertsService: AlertsService) {
  }

  ngOnInit() {
    this.alerts = this.alertsService.alerts;
  }

  addAlert(alert: IAlert) {
    this.alertsService.add(alert);  // Add to padding here?
  }

  closeAlert(i: number) {
    this.alertsService.close(i);   // Remove padding here?
  }
}

两个组件都应该注入 AlertsServiceAlertsComponent 订阅 AlertsService 提供的可观察对象。 NavbarComponent 通过 observable 发出值以通知 AlertsComponent 要采取的行动。

示例见https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service