我是Angular2上的新手,我必须在 @angular/材料等UI组件上构建一个模块,以便我的队友只能关心API,而不是对它们展示比我使用的UI框架。
例如,当他们想使用alert
函数时,他们可以简单地使用import { Alert } from './Alert'
,并以某种方式在其代码中使用,而忽略UI框架是什么。即使我们更改其UI框架(或主题),业务逻辑也可以保持不变。
我已经搜索了很多有关扩展UI组件的信息,并与组件共享一个共享的ngmodule。而且仍然不确定如何制作。特别是使用 @angular/材料。
您的帮助非常感谢!
您确定不能简单地使用组件和服务来实现这一目标吗?当您创建一个Angular2组件时,您可以将您的"逻辑"和两个不同文件中的模板代码具有,因此可以随时修改模板(UI/主题)而不会影响"逻辑"。然后,您可以创建一个警报服务,以管理其他组件和警报组件之间的通信。这是一个例子...
对于组件警报,您可以拥有两个单独的文件altert.html和arter.ts-所有UI(HTML)代码都在内部警报中。如下:
警报模板: 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();
}
}
现在有关警报服务,请参见下文。我不会对此解释太多,因为Mark在此文章中已经做得很好:委托:eventemitter或在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)
}
}
因此,您的同事只需在应用程序中的某个高级别中包括您的自定义组件即可。在他们想要显示警报的特定组件中,可以简单地注入customAlertService并通过在customAlertSercice上调用setAlertMessage()来更新警报消息,从而依次通知您的custicAlert组件,该组件将渲染警报...