警报和导航栏模块/组件/服务:如何解耦视图?

时间:2016-12-05 03:25:19

标签: twitter-bootstrap angular angular2-template angular2-directives angular2-services

所以我曾经在Sub getEmails() Dim toNames As Range Set toNames = Range("D25") ' names input by user Dim names As Range Set names = Range("A25:A39") ' names range from lookup table Dim splitNames splitNames = Split(toNames, ",") Dim selectedEmails As String Dim findRange As Range For i = 0 To UBound(splitNames) ' find the range matching the name findRange = names.Find(What:=splitNames(i), LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) ' if match found, get the email and store to selected emails variable If Not findRange Is Nothing Then selectedEmails = selectedEmails & Range("B" & findRange.Row) & ";" End If Next i 'output emails Range("D26") = selectedEmails End Sub

中使用此功能
app.component.ts

但它并不属于那里。它属于服务吗? - 可能不是,该服务意味着与视图分离。 - 我可以将addNewAlert() { this.appService.navbarPadding += 81; this.alertsService.alerts.push({ type: 'info', msg: 'INFO' }); } 导入我的其他alerts.component.ts吗?

navbar.component.ts

Component

alerts.service.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.component.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);
  }
}

1 个答案:

答案 0 :(得分:1)

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

有关示例,请参阅https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service