下面是一个示例解决方案,演示如何在Angular/Typescript中的数组服务中添加时间戳:
ArrayService
的数组服务,并导入Injectable
和Observable
:import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ArrayService {
private array: any[] = [];
constructor() { }
// 添加元素到数组并返回时间戳
addElement(element: any): number {
const timestamp = Date.now();
this.array.push({ element, timestamp });
return timestamp;
}
// 获取数组
getArray(): Observable {
return new Observable(observer => {
observer.next(this.array);
observer.complete();
});
}
}
ArrayService
:import { Component, OnInit } from '@angular/core';
import { ArrayService } from './array.service';
@Component({
selector: 'app-array',
template: `
{{ item.element }} - {{ item.timestamp | date:'medium' }}
`
})
export class ArrayComponent implements OnInit {
array$ = this.arrayService.getArray();
constructor(private arrayService: ArrayService) { }
ngOnInit() {
// 添加示例元素到数组
this.arrayService.addElement('Example Element');
}
}
ArrayService
:import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ArrayService } from './array.service';
import { ArrayComponent } from './array.component';
@NgModule({
imports: [BrowserModule],
declarations: [ArrayComponent],
providers: [ArrayService],
bootstrap: [ArrayComponent]
})
export class AppModule { }
通过以上步骤,你可以在ArrayService
中添加一个元素到数组,并附带一个时间戳。在组件中,通过array$
属性订阅数组的变化,并在模板中使用*ngFor
循环遍历显示数组元素和时间戳。
上一篇:Angular/Typescript - 在OnDestroy时获取时间戳
下一篇:Angular/Typescript - 这个表达式不可构造。类型 'MoveDataClass' 没有构造签名。