Moment() is not defined in Angular

Alo*_*lok 4 angular

I have a working Angular project, and I have been given the work to carry forward the work. Since this is a small yet confusing problem for me, after a lot of research I have failed myself to get to the result.

In my project, we have used the moment in the app.component.ts, and used the code. The code is below

1. app.component.ts

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
declare var moment: any;

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})

export class AppComponent {

 year = moment().format("YYYY")

 constructor(private router: Router) {}
}
Run Code Online (Sandbox Code Playgroud)

2. app.component.html

<router-outlet></router-outlet>

<hr>

<section class='container footer'>
 <div class="row">
  <div class="col-md-6">
   <p>Hello {{year}}</p>
  </div>
 </div>
</section>
Run Code Online (Sandbox Code Playgroud)

Error comes in this line : year = moment().format("YYYY")

As soon as I comment the line, it works, but it is not working when the code includes this.

The error is this :

ERROR ReferenceError: moment is not defined
at new AppComponent (app.component.ts:12)
at createClass (core.es5.js:10925)
at createDirectiveInstance (core.es5.js:10756)
at createViewNodes (core.es5.js:12197)
at createRootView (core.es5.js:12092)
at callWithDebugContext (core.es5.js:13475)
at Object.debugCreateRootView [as createRootView] (core.es5.js:12792)
at ComponentFactory_.webpackJsonp.../../../core/@angular/core.es5.js.ComponentFactory_.create (core.es5.js:9864)
at ComponentFactoryBoundToModule.webpackJsonp.../../../core/@angular/core.es5.js.ComponentFactoryBoundToModule.create (core.es5.js:3333)
at ApplicationRef_.webpackJsonp.../../../core/@angular/core.es5.js.ApplicationRef_.bootstrap (core.es5.js:4768)
Run Code Online (Sandbox Code Playgroud)

After the research, I have tried some more thing, and in my knowledge the thing is not working because the moment is getting loaded before the window loads.

But couldn't find any possible way to rectify it. To your surprise it is working fine on our web, but when I run on my local box it is giving out the same error.

感谢帮助。谢谢

Kri*_*ore 8

安装时刻 npm install moment --save

使用 import * as moment from 'moment';

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import * as moment from 'moment';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})

export class AppComponent {

 year = moment().format("YYYY")

 constructor(private router: Router) {}
}
Run Code Online (Sandbox Code Playgroud)