javascript - Angular 2相同的组件在多个地方具有不同的业务逻辑

标签 javascript angular typescript generic-programming use-case

抱歉问题太长了。我有一些设计问题。

我有一个组件,它将 roomView 数组作为 @Input 并在 HTML 页面中显示它们。

export class RoomView {
"id": string,
"name": string,
"markerIcon": string,
"backgroundColorClass": string
}

room-browser.component.ts

@Component({
    selector: 'room-browser',
    templateUrl: 'room-browser.component.html',
})
export class RoomBrowserComponent {
    @Input() roomsList: RoomView[]: = [];
}

room-browser.component.html

<div *ngFor="let room of roomsList">
    <div class="room.backgroundColorClass">
    {{room.name}}
    <i class="{{room.markerIcon}}"></i>
    </div>

enter image description here

我的通用房间组件向房间浏览器提供 roomView

generic-room.component.ts

@Component({
    selector: 'room',
    templateUrl: 'room.html',
})
export class GenericRoomComponent implements OnInit {

    @Input() source: string;

    private roomView: RoomView[] = [];

    ngOnInit() {
        this.roomView = // i am getting this from backed successfully
        // here I need to decide marker icon and background color class based on some criteria which differs from page to page
        // I have different sections like space, energy, maintenance etc...
        // for space, needs to get space usage for rooms from backend and then decide color
        // for energy, needs to get energy usage and decide the colors
        // for maintenance, needs get devices information of rooms and decide color

    //I want to avoid something like this
    if (this.source === 'space') {
         // get space usage
    } else if (this.source === 'energy') {
         // get space usage
    } else if (this.source === 'maintenance') {
         // get device info and decide color
    }
    }

}

room.html

<room-browser [roomsList]="roomView"></room-browser>

space.html

<room [source]="space"></room>

energy.html

<room [source]="energy"></room>

ma​​intenance.html

<room [source]="maintenance"></room>

我需要根据页面之间不同的一些标准来决定标记图标和背景颜色类别。

我有不同的部分,例如空间、能源、维护等...对于空间,需要从后端获取房间的空间使用情况,然后决定颜色,对于能源需要获取能源使用情况并决定颜色,对于维护需求需要获取房间的设备信息并决定颜色

那么我如何以及在哪里可以在通用组件内实现此用例特定逻辑?

最佳答案

我不确定我完全理解您的场景,但您可以为每种颜色向 GenericRoomComponent 添加颜色属性,并通过附加 @Input 属性将它们传递给子组件。

或者您可以构建一个保留这些值的服务,并让每个子组件读取这些值。

关于javascript - Angular 2相同的组件在多个地方具有不同的业务逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44762471/

相关文章:

javascript - AngularJS:可以在同一个指令中清理和链接吗?

javascript - 在 AngularJS 中创建一个 Q promise 函数调用阻塞

cookies - angular2,带有凭据的http。无法添加 cookie

.net - 使用 ASP.NET Core 的 Angular 项目模板。 API测试

angular - 在 Angular2 中,mailto 链接被识别为组件路由

javascript - Angular 6 : How to set response type as text while making http call

javascript - 仅在页面第一次加载时在第一张幻灯片上添加类

javascript - React Native - 设置两个函数的顺序

typescript 多种类型检查功能

javascript - 在 typescript 中输入交集