2017-03-07 30 views
-1

我在Angular2新,以及關於API暴露給他們,我必須建立在UI組件的模塊,比如@角/材料,讓我的隊友只能照顧,而不是我使用的UI框架。在Angular2,如何去耦UI模塊與邏輯

例如,當他們想要使用alert函數時,他們可以簡單地使用import { Alert } from './Alert',並以某種方式在代碼中使用,忽略了什麼UI框架。儘管我們改變了其UI框架(或主題),但業務邏輯可以保持不變。

我GOOGLE了很多關於延長UI組件,使得共享NgModule與組件。並且仍然不確定如何製作它。尤其是使用@ angular/material。

您的幫助表示感謝!

回答

0

你肯定你不能簡單地使用組件和服務來實現這一目標?當你創建一個Angular2組件時,你可以將你的「邏輯」和模板代碼放在兩個不同的文件中,因此可以隨時修改你的模板(UI /主題),而不會影響「邏輯」。然後,您可以創建警報服務來管理其他組件和警報組件之間的通信。下面是一個例子...

對於一個部件警示你可以有兩個單獨的文件altert.html和alert.ts - 所有的UI(HTML)代碼走了進去alert.html和所有邏輯應是alert.ts ...您的代碼將然後類似於下面:

通知模板:alert.html

<div id="card-alert" *ngIf="alertMessage != "" && alertMessage != null"> 
     <p>ALERT: {{ alertMessage }}</p> 
    </div> 

警報邏輯:alert.ts

import {Component} from '@angular/core'; 
    import {CustomAlertService} from './alert.service'; 

    @Component({ 
     selector: 'alert', 
     templateUrl: './alert.html' 
    }) 
    export class CustomAlert { 
     alertSubscription: any; // this will allow you to reference the subscription in order to be able to unsubscribe later 

     alertMessage: String; 

     constructor(private alertService: CustomAlertService) { // you could also have an alert service hooked up here 
     this.alertSubscription = this.alertService.alertMessage$.subscribe(
      message => 
      this.alertMessage = message; // update current alert message to be displayed 
      ); 
     } 

    ngOnDestroy() { 
    // you want to unsubscribe when component is destroyed to prevent potential memory leak 
    this.alertSubscription.unsubscribe(); 
    } 
    } 

現在需要提醒服務,請參閱下文。我不會在這方面解釋太多,因爲在這篇SO文章中標記爲:Delegation: EventEmitter or Observable in Angular2

警報邏輯(服務):alert.service.ts

import {Injectable} from '@angular/core'; 
import {Observable} from 'rxjs/Observable'; 
import {Observer} from 'rxjs/Observer'; 

@Injectable() 
export class CustomAlertService { 
    alertMessage$: Obersvable<string>; 
    private _observer: Observer; 

    constructor() { 
    this.alertMessage$ = new Observable(observer => 
     this._observer = observer).share(); 
} 

    setAlertMessage(alert: String) { 
     this._observer.next(alert) 
    } 

} 

那麼你的同事就只會在應用程序內的一些高層次的CustomAlert組件。他們想要顯示警報的特定組件內部,則可以簡單地注入CustomAlertService並通過調用CustomAlertSercice的setAlertMessage(),這將反過來通知您的CustomAlert組件,它會使警報更新警報消息...