简体   繁体   English

如何在 nestjs 应用程序中使用 moment

[英]How to use moment in nestjs application

I want to use momentjs in a nestjs app, and also be able to test my services.我想在 nestjs 应用程序中使用 momentjs,并且还能够测试我的服务。 So I provided momentjs as below in my module所以我在我的模块中提供了如下的 momentjs

providers: [
    {
      provide: 'MomentWrapper',
      useFactory: async () => moment(),
      scope: Scope.REQUEST,
    },
  ],

and in my service在我的服务中

    constructor(
        @Inject('MomentWrapper') private momentWrapper: moment.Moment
    )

Then I have a method like this然后我有这样的方法

    private calculateNextRun(every: number, period: SchedulePeriod): string {
        const currentDate = this.momentWrapper.tz('America/Toronto');
        let nextDate = null;

        nextDate = currentDate.add(every, period);
        console.log(currentDate.format(), nextDate.format(), every, period, );

        return nextDate.toISOString();
    }

This method will be called in a loop, and supposed to get the current date and add some days/weeks/.. to it and return it.此方法将在循环中调用,并应该获取当前日期并向其添加一些天/周/.. 并返回它。

The issue is it keeps the old value so each time it goes into the method is not starting from current date问题是它保留了旧值,因此每次进入该方法时都不是从当前日期开始

console output控制台 output

2020-01-25T16:39:19-05:00 2020-01-25T16:39:19-05:00 6 d
2020-02-15T16:39:19-05:00 2020-02-15T16:39:19-05:00 3 w
2020-02-16T16:39:19-05:00 2020-02-16T16:39:19-05:00 1 d

If you see first date, which is currentDate keep changing如果您看到第一个日期,即currentDate不断变化

Is there any way to overcome this issue, without creating a new service like this有没有办法解决这个问题,而无需创建这样的新服务

import * as moment from 'moment-timezone';
@Injectable()
export class MomentService {
    moment(): moment.Moment {
        return moment();
    }
}

You should create a new moment instance for each function call and not reuse the same instance of your provider singleton.您应该为每个函数调用创建一个新的 moment 实例,而不是重用提供者单例的相同实例。 So provide moment instead of moment() :所以提供moment而不是moment()

providers: [
    {
      provide: 'MomentWrapper',
      useValue: moment
    },
  ],

This works fine for me:这对我来说很好用:

// in some *.service.ts
import * as moment form 'moment';


{ userIsRegistredOn: moment()}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM