【问题标题】:angular 2 same component in multiple places with different business logic具有不同业务逻辑的多个地方的角度2相同组件
【发布时间】:2017-06-26 14:49:55
【问题描述】:

对不起,问题的长度。我有一些设计问题。

我有一个组件,它将 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>

我的通用房间组件为房间浏览器提供房间视图

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>

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

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

那么如何以及在哪里可以在通用组件中实现这个用例特定的逻辑?

【问题讨论】:

    标签: javascript angular typescript generic-programming use-case


    【解决方案1】:

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

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

    【讨论】:

    • 要添加颜色属性,我有不同的逻辑,具体取决于我是在空间、能源还是维护中使用房间组件。对于空间,我需要从后端获取空间使用情况,并决定使用时间少于 2 小时的颜色,然后是红色等。对于维护部分,我需要获取房间设备,如果设备出现错误,则将颜色标记为红色。所以我的问题是在哪里以及如何实现这个逻辑?
    【解决方案2】:

    如果您想跨多个模块使用一个组件,您需要创建一个“共享”模块并将该组件添加到共享模块的导出中。然后将该共享模块添加到其他模块导入中。

    【讨论】:

      猜你喜欢
      • 2011-08-15
      • 2023-01-18
      • 2019-01-30
      • 1970-01-01
      • 2018-05-03
      • 2017-06-15
      • 1970-01-01
      • 1970-01-01
      • 2014-02-22
      相关资源
      最近更新 更多