2017-03-07 5 views
-1

私はAngular2の新機能です。@ angular/materialなどのUIコンポーネントでモジュールをビルドする必要がありますので、チームメイトはAPI露出のみを気にすることができます私が使用するUIフレームワークではなく、in Angular2、UIモジュールをロジックでデカップリングする方法

たとえば、alert関数を使用する場合は、単にimport { Alert } from './Alert'を使用して、何らかのUIフレームワークを無視してコード内で使用します。 UIフレームワーク(またはテーマ)を変更しても、ビジネスロジックは変わりません。

私は、UIコンポーネントを拡張し、コンポーネントで共有されたNgModuleを作ることについて多くのことを尋ねました。そしてそれを作る方法についてまだよくわからない。特に@角度/材質で作業する。

ご協力いただき誠にありがとうございます。

答えて

0

これを達成するために単にコンポーネントとサービスを使用することはできませんか? Angular2コンポーネントを作成するときは、 "ロジック"と2つの異なるファイルにテンプレートコードを含めることができます。したがって、 "ロジック"に影響を与えずに、テンプレート(UI /テーマ)をいつでも変更できます。アラートサービスを作成して、他のコンポーネントとアラートコンポーネント間の通信を管理することができます。ここに例があります...

アラートの場合、altert.htmlとalert.tsという2つの別々のファイルがあります。すべてのUI(html)コードはalert.html内にあり、すべてのロジックはalert.tsに入ります

ALERTテンプレート:ALERTロジック

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

alert.html:...あなたのコードは、以下のようになります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ロジック(サービス):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()を呼び出します。このアラートメッセージは、CustomAlertSerciceに対して通知します。

関連する問題