2017-03-07 1 views
-1

저는 Angular2에 새로운 기능입니다. @ angle/material과 같은 UI 구성 요소를 기반으로 모듈을 만들어야합니다. 따라서 팀원은 API 노출에만 관심을 가질 수 있습니다. , 내가 사용하는 UI 프레임 워크보다는.in Angular2, UI 모듈을 로직으로 분리하는 방법

예를 들어, alert 함수를 사용하려는 경우 그들은 단지 import { Alert } from './Alert'을 사용할 수 있으며 어떤 식 으로든 UI 프레임 워크를 무시하고 코드에서 사용합니다. UI 프레임 워크 (또는 테마)를 변경하더라도 비즈니스 로직은 동일하게 유지 될 수 있습니다.

UI 구성 요소를 확장하여 구성 요소가있는 공유 NgModule을 만드는 방법에 대해 많이 살펴 보았습니다. 그리고 그것을 만드는 방법에 대해 아직도 확실하지 않습니다. 특히 @ angular/material으로 작업하십시오.

귀하의 도움에 감사드립니다!

답변

0

이것을 달성하기 위해 구성 요소와 서비스를 단순히 사용할 수는 없습니까? Angular2 구성 요소를 만들 때 "논리"와 두 개의 다른 파일에있는 템플릿 코드를 가질 수 있으므로 "논리"에 영향을주지 않고 항상 원하는대로 템플릿 (UI/테마)을 수정할 수 있습니다. 그런 다음 다른 구성 요소와 경고 구성 요소 간의 통신을 관리하는 경고 서비스를 만들 수 있습니다. 다음은 예제입니다 ...

구성 요소 경보의 경우 두 개의 개별 파일 altert.html과 alert.ts가있을 수 있습니다. 모든 UI (html) 코드는 alert.html 내부에 있으며 모든 논리는 alert.ts에 있습니다.

ALERT 템플릿 : : ALERT의 LOGIC

<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(); 
    } 
    } 

경고 서비스는 아래를 참조하십시오. 이것에 관해서는 여기에있는 문서 (Delegation: EventEmitter or Observable in Angular2)에 잘 설명되어 있기 때문에 여기서는 그다지 설명하지 않겠습니다.

ALERT의 LOGIC (서비스) : 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를 삽입하고 경고를 렌더링하는 CustomAlert 구성 요소에 통보 할 CustomAlertSercice에서 setAlertMessage()를 호출하여 경고 메시지를 업데이트 할 수 있습니다.

관련 문제