我需要制作一个红绿灯,从0到10分钟是绿色,从10到20黄色,从20到30红色,时间是服务
到目前为止,这是我的代码
这是组件
import {
Component,
OnInit,
Input
} from '@angular/core';
import {
TiempoService
} from "app/servicios/tiempo.service"
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit {
@Input() tiemposervice: TiempoService;
constructor() {}
ngOnInit() {
}
}

这是HTML
<div class="row">
<div class="small-12 medium-6 columns">
<span>Tiempo transcurrido</span>
<h5>{{tiempoTranscurrido | date:'mm:ss'}}</h5>
</div>
</div>
&#13;
这是服务
import {
Injectable
} from '@angular/core';
import Rx from 'Rx';
@Injectable()
export class TiempoService {
tiempoTranscurrido: number;
constructor() {}
ngOnInit() {
}
tiempoTotal() {
Rx.Observable.interval(1000).subscribe(segundos => {
this.tiempoTranscurrido = segundos * 1000;
})
}
}
&#13;
非常感谢你的帮助。
答案 0 :(得分:1)
我建议你需要这样的东西:
服务:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable()
export class LightService {
getLight(interval): Observable<string> {
return Observable.interval(interval)
.timeInterval()
.map(time => {
if(time.value % 3 === 2) {
return 'green';
} else if(time.value % 3 === 0) {
return 'yellow';
} else if (time.value % 3 === 1) {
return 'red';
}
});
}
}
组件:
import { Component, OnInit } from '@angular/core';
import { LightService } from './light.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [ LightService ]
})
export class AppComponent implements OnInit {
light: string = "green";
constructor(private lightService: LightService) {}
ngOnInit() {
this.lightService
.getLight(10000) // 10 seconds interval
.subscribe(light => this.light = light);
}
}
模板:
<h1>
{{ light }}
</h1>
<ul>
<li *ngIf="light === 'green'" class="green"></li>
<li *ngIf="light === 'yellow'" class="yellow"></li>
<li *ngIf="light === 'red'" class="red"></li>
</ul>
样式:
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
li {
width: 64px;
height: 64px;
border-radius: 50%;
border: 1px solid black;
}
.green {
background-color: green;
}
.yellow {
background-color: yellow;
}
.red {
background-color: red;
}
如果您只需要在添加拍摄操作符后显示灯光:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable()
export class LightService {
getLight(interval): Observable<string> {
return Observable.interval(interval)
.timeInterval()
.map(time => {
if(time.value % 3 === 2) {
return 'green';
} else if(time.value % 3 === 0) {
return 'yellow';
} else if (time.value % 3 === 1) {
return 'red';
}
})
.take(2);
}
}