我正在开发新的Angular项目,其中包含有关电影的信息。创建新的不同日期时,我的movie.service.ts中有一个。
这是我的错误
ERROR TypeError: Cannot read property 'year' of undefined
at new MovieService (movie.service.ts:17)
at core.js:1461
at _callFactory (core.js:8223)
at _createProviderInstance (core.js:8181)
at resolveNgModuleDep (core.js:8156)
at NgModuleRef_.push../node_modules/@angular/core/fesm5/core.js.NgModuleRef_.get (core.js:8849)
at resolveDep (core.js:9214)
at createClass (core.js:9086)
at createDirectiveInstance (core.js:8971)
at createViewNodes (core.js:10191)
我想在过去的几个月里在剧院放映最近的电影。这是我的src代码
import { Injectable } from '@angular/core';
import { Jsonp } from "@angular/http";
import { HttpClient } from "@angular/common/http";
import {map} from 'rxjs/operators';
import { getLocaleDayNames } from '../../node_modules/@angular/common';
@Injectable({
providedIn: 'root'
})
export class MovieService {
date = new Date();
today = {
day: this.date.getDate(),
month: this.date.getMonth(),
year: this.date.getFullYear(),
now: `${this.today.year}-${this.today.month}-${this.today.day}`,
then: `${this.today.year}-${this.today.month - 1}-${this.today.day}`
};
apiKey: string = '9e2ecb8b71753c6759e1c9f2cb4f961a';
constructor(private __jsonp: Jsonp) {
console.log(`${this.today.now} and ${this.today.then}`);
}
getPopular(){
this.__jsonp.get('https://api.themoviedb.org/3/discover/movie?callback=JSONP_CALLBACK&sort_by=popularity.desc')
.pipe(map(res => res.json()));
}
getInTheatres(){
this.__jsonp.get('https://api.themoviedb.org/3//discover/movie?primary_release_date.gte=2014-09-15&primary_release_date.lte=2014-10-22')
}
}
您试图在创建变量之前初始化变量。实现它的最简单方法是在构造函数中执行。像这样的东西:
today;
constructor() {
const date = new Date();
const dmy = {
day: date.getDate(),
month: date.getMonth(),
year: date.getFullYear(),
}
this.today = {
day: `${dmy.day}`,
month: `${dmy.month}`,
year: `${dmy.year}`,
now: `${dmy.year}-${dmy.month}-${dmy.day}`,
then: `${dmy.year}-${dmy.month - 1}-${dmy.day}`
};
console.log(this.today)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句