我在服务上有一个从服务器获取时间的方法,我打算在自定义管道中使用它。管道的目的是将时间戳记与当前时间进行比较,并以人类可读的格式返回它。
服务
export class TimeService{
currentServerTime;
fetchCurrentTimeStamp(){
//http request using Observable
return sendGETRequest(.....).map(data => {
this.currentServerTime = data;
return this.currentServerTime;
})
}
}
Run Code Online (Sandbox Code Playgroud)
管
export class GetTimeFromNowPipe implements PipeTransform{
fromNow;
currentServerTime: number;
constructor(private timeService: TimeService, private appSettings: AppSettings){}
transform(value: number){
var currentTime;
this.timeService.fetchCurrentTimestamp().subscribe(data => {
currentTime = data
if(!value) return "";
if(value){
let newDate = moment.unix(value);
this.fromNow = newDate.from(moment.unix(currentTime), true);
}
return this.fromNow;
});
}
}
Run Code Online (Sandbox Code Playgroud)
的HTML
<ul>
<li *ngFor = "let model of models">
<span>{{model.created | getTimeFromNow}}</span>
</li>
</ul> …Run Code Online (Sandbox Code Playgroud) 我有一个看起来像这样的子组件
子组件
@Component({
selector: 'child-component',
//TemplateUrl, Styles and Providers
})
export Class ChildComponent implements OnInit{
@Input()
arrayToGet; //An array that I want to pass from Parent to child
ngOnInit(){
console.log('The Array I got is ', this.arrayToGet); //Undefined, Tried even with setTimeout
}
//A bunch of methods to work with the array I get
}
Run Code Online (Sandbox Code Playgroud)
父组件
@Component({
selector: 'parent-component',
template: '<div>
<child-component [arrayToGet]="models"></child-component>
</div>',
//A bunch of Styles and Providers
})
export class ParentComponent{
models;
constructor(......){}
ngOnInit(){
//Get an array from …Run Code Online (Sandbox Code Playgroud)