我正在处理angular 8和ionic 4项目,但是当我在设备中运行该项目时,它给出错误无法在SelectedDateService.ngOnInit()读取null的属性'0'。在此代码中,我们可以将旧代码从ionic3和angular7版本中移出到版本inic4和angular 8的新代码,但我不明白为什么会出现此错误以及如何解决。
有身体可以引导我吗?

SelectedDateService

import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import * as moment from 'moment'

@Injectable({
  providedIn: 'root'
})
export class SelectedDateService {
  selectedProfile: any;
  timeObj: any;
  dateYesterday: any;
  dateLastMonthTo: any;
  dateLastWeekTo: any;
  dateThisMonthTo: any;
  dateLast30DaysTo: any;
  dateLastMonthFrom: any;
  dateLastWeekFrom: any;
  dateThisMonthFrom: any;
  dateLast30DaysFrom: any;
  usersProfiles: any;
  selectedDate: any;
  selectedDateLabel: any;
  providerObj: any = {}

  lastWeek: any;
  lastMonth: any;
  yesterday: any;
  thisMonth: any;
  last30Days: any;
  customRange: any;
  constructor(translate:  TranslateService ) {
    translate.get("LAST_WEEK").subscribe(value => {this.lastWeek = value})
        translate.get("LAST_MONTH").subscribe(value => {this.lastMonth = value})
        translate.get("YESTERDAY").subscribe(value => {this.yesterday = value})
        translate.get("THIS_MONTH").subscribe(value => {this.thisMonth = value})
        translate.get("LAST_30_DAYS").subscribe(value => {this.last30Days = value})
        translate.get("CUSTOM_RANGE").subscribe(value => {this.customRange = value})
        this.ngOnInit();
   }
   ngOnInit() : void
   {
    this.usersProfiles = JSON.parse(window.localStorage.getItem('profiles'));
    this.selectedProfile = JSON.parse(window.localStorage.getItem('lastUsedProfile')) || this.usersProfiles[0];
    this.timeObj =  this.setTimeObj();
   }
   setTimeObj() {
    let obj = {
      0: {
          'label': this.lastWeek,
          'timeTo': this.dateLastWeekTo,
          'timeFrom': this.dateLastWeekFrom,
          'id': 'last-week'
        },
        1: {
          'label': this.yesterday,
          'timeFrom': this.dateYesterday,
          'id': 'yesterday'
        },
        2: {
          'label': this.last30Days,
          'timeTo': this.dateLastWeekTo,
          'timeFrom': this.dateLastWeekFrom,
          'id': 'last-30-days'
        },
        3: {
          'label': this.lastMonth,
          'timeTo': this.dateLastMonthTo,
          'timeFrom': this.dateLastMonthFrom,
          'id': 'last-month'
        },
        4: {
          'label': this.thisMonth,
          'timeTo': this.dateThisMonthTo,
          'timeFrom': this.dateThisMonthFrom,
          'id': 'this-month'
        }
    };
    return obj
}

getTimeVariables() {
    let lan = window.navigator.language;
    if (lan.includes('ES')){
       moment.locale('ES');
    } else{
       moment.locale('EN');
    }
    let month = (moment(Date.now()).month()) != 10 && (moment(Date.now()).month()) != 11 && (moment(Date.now()).month()) != 12 ? '0' : '';
    let monthNow = (moment(Date.now()).month() + 1) != 10 && (moment(Date.now()).month() + 1) != 11 && (moment(Date.now()).month() + 1) != 12 ? '0' : '';
    let startDate = moment(Date.now()).year().toString() + month + moment(Date.now()).month().toString() + '01';
    this.dateThisMonthTo = moment(Date.now() - 1 * 24 * 3600 * 1000).format('DD-MMMM');
    this.dateThisMonthFrom = moment(moment(Date.now()).year().toString() + monthNow + (moment(Date.now()).month() + 1 ).toString() + '01').format('DD-MMMM');
    this.dateYesterday =  moment(Date.now() - 1 * 24 * 3600 * 1000).format('DD-MMMM');
    this.dateLastMonthTo = moment(startDate).endOf('month').format('DD-MMMM');
    this.dateLastMonthFrom = moment(moment(Date.now()).year().toString() + month + moment(Date.now()).month().toString() + '01').format('DD-MMMM');
    this.dateLastWeekTo = moment(Date.now() - 1 * 24 * 3600 * 1000).format('DD-MMMM');
    this.dateLastWeekFrom = moment(Date.now() - 6 * 24 * 3600 * 1000).format('DD-MMMM');
    this.dateLast30DaysTo = moment(Date.now() - 1 * 24 * 3600 * 1000).format('DD-MMMM');
    this.dateLast30DaysFrom = moment(Date.now() - 31 * 24 * 3600 * 1000).format('DD-MMMM');
 }


/*
** Returns data object of selected time
*/
getDateObj(time) {
    let dateArr = [];
    let dateFrom;
    let dateTo;
    let monthNow = (moment(Date.now()).month() + 1) != 10 && (moment(Date.now()).month() + 1) != 11 && (moment(Date.now()).month() + 1) != 12 ? '0' : '';

    if (time == 'this-month') {
      dateFrom = moment(Date.now()).year().toString() + monthNow + (moment(Date.now()).month() +1).toString() + '01';
      dateTo = moment(Date.now() - 1 * 24 * 3600 * 1000).format('YYYYMMDD');
    } else if (time == 'yesterday') {
      dateFrom = moment(Date.now() - 1 * 24 * 3600 * 1000).format('YYYYMMDD');
      dateTo =  moment(Date.now() - 1 * 24 * 3600 * 1000).format('YYYYMMDD');
    } else if (time == 'last-month') {
      dateFrom = moment(moment().subtract(1, 'month')).format('YYYYMM').toString() + '01';
      dateTo = moment(moment().subtract(1, 'month').endOf('month')).format('YYYYMMDD');
    } else if (time == 'last-30-days') {
      dateFrom = moment(Date.now() - 31 * 24 * 3600 * 1000).format('YYYYMMDD');
      dateTo =  moment(Date.now() - 1 * 24 * 3600 * 1000).format('YYYYMMDD');
    } else if (time == 'last-week') {
        dateFrom = moment(Date.now() - 7 * 24 * 3600 * 1000).format('YYYYMMDD');
        dateTo =  moment(Date.now() - 1 * 24 * 3600 * 1000).format('YYYYMMDD');
    } else if (time == 'custom-range') {
      dateFrom = moment(JSON.parse(window.localStorage.getItem('customRange'))[0]).format();
      dateTo = moment(JSON.parse(window.localStorage.getItem('customRange'))[1]).format();
    } else {
      dateFrom = moment(Date.now() - 7 * 24 * 3600 * 1000).format('YYYYMMDD');
        dateTo =  moment(Date.now() - 1 * 24 * 3600 * 1000).format('YYYYMMDD');
    }
    dateArr.push(dateFrom, dateTo);
    return dateArr
}

/*
** Returns value of selected date
*/

getSelectedDate(time) {
  let lan = window.navigator.language;
    let dateArr;
    let dateFrom;
    let dateTo;
  let monthNow = (moment(Date.now()).month() + 1) != 10 && (moment(Date.now()).month() + 1) != 11 && (moment(Date.now()).month() + 1) != 12 ? '0' : '';
  if (lan.includes('ES')){
      moment.locale('ES');
  } else{
      moment.locale('EN');
  }

    if (time == 'this-month') {
        dateFrom = moment(moment(Date.now()).year().toString() + monthNow + (moment(Date.now()).month() +1).toString() + '01').format('DD-MMMM');
        dateTo = moment(Date.now() - 1 * 24 * 3600 * 1000).format('DD-MMMM');
    } else if (time == 'yesterday') {
        dateFrom = moment(Date.now() - 1 * 24 * 3600 * 1000).format('DD-MMMM');
        dateTo =  moment(Date.now() - 1 * 24 * 3600 * 1000).format('DD-MMMM');
    } else if (time == 'last-month') {
        dateFrom = '01-' + moment(moment().subtract(1, 'month')).format('MMMM').toString();
        dateTo = moment(moment().subtract(1, 'month').endOf('month')).format('DD-MMMM');
    } else if (time == 'last-30-days') {
        dateFrom = moment(Date.now() - 31 * 24 * 3600 * 1000).format('DD-MMMM');
        dateTo =  moment(Date.now() - 1 * 24 * 3600 * 1000).format('DD-MMMM');
    } else if (time == 'last-week') {
        dateFrom = moment(Date.now() - 7 * 24 * 3600 * 1000).format('DD-MMMM');
        dateTo =  moment(Date.now() - 1 * 24 * 3600 * 1000).format('DD-MMMM');
    } else if (time == 'custom-range') {
      dateFrom = moment(JSON.parse(window.localStorage.getItem('customRange'))[0]).format('DD MMMM');
      dateTo = moment(JSON.parse(window.localStorage.getItem('customRange'))[1]).format('DD MMMM');
    } else {
      dateFrom = moment(Date.now() - 7 * 24 * 3600 * 1000).format('DD-MMMM');
        dateTo =  moment(Date.now() - 1 * 24 * 3600 * 1000).format('DD-MMMM');
    }
    dateArr = dateFrom + ' - ' + dateTo;
    return dateArr
}
}


app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy, RouterModule } from '@angular/router';

import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { LayoutComponent } from './components/layout/layout.component';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { AngularFireModule } from '@angular/fire';
import { AngularFirestoreModule } from '@angular/fire/firestore';

import { Firebase } from "@ionic-native/firebase/ngx";
import { UniqueDeviceID } from '@ionic-native/unique-device-id/ngx';
import { Device } from '@ionic-native/device/ngx';
import { TwitterConnect } from '@ionic-native/twitter-connect/ngx';
import { Facebook } from '@ionic-native/facebook/ngx';
import { WelcomePage } from './pages/welcome/welcome.page';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';

export const firebaseConfig = {
  apiKey: "AIzaSyDDVrXtXhTO60cYivkRwaU5XoM0CnrMyOI",
  authDomain: "metricool-cc74e.firebaseapp.com",
  databaseURL: "https://metricool-cc74e.firebaseio.com",
  projectId: "metricool-cc74e",
  storageBucket: "metricool-cc74e.appspot.com",
  messagingSenderId: "352613795929"
};

@NgModule({
  declarations: [
    AppComponent,
    LayoutComponent,
    WelcomePage
  ],
  entryComponents: [],
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    BrowserModule,
    HttpClientModule,
    AngularFireModule.initializeApp(firebaseConfig),
    AngularFirestoreModule,

    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: createTranslateLoader,
        deps: [HttpClient]
      }
    }),
    IonicModule.forRoot(),
    AppRoutingModule,
  ],
  providers: [
    StatusBar,
    SplashScreen,
    Firebase,
    UniqueDeviceID,
    Device,
    TwitterConnect,
    Facebook,
    InAppBrowser,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }


export function createTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http);
}

最佳答案

SelectedDateService可能正在与您想象的位置不同的地方运行,因为它是创建的注入服务。这意味着。

也可能是您到处都有此错误,不仅是在设备上进行测试,而且您的浏览器已经保存了值。尝试清除缓存并在浏览器中重新加载它,您可能会看到相同的错误。

您需要考虑在首次加载时以及现有用户遇到初始空数据集的机会。

在此行中:

this.usersProfiles = JSON.parse(window.localStorage.getItem('profiles'));


您需要-寻找一种方法来保证它具有值,或者将其更改为类似以下内容:

this.usersProfiles = JSON.parse(window.localStorage.getItem('profiles') || { /* some default json */ });


另外,考虑使用Ionic Storage而不是直接使用localStorage,因为它提供更好的跨设备/平台兼容性:


Data Storage - Ionic Documentation

关于javascript - TypeError:无法在SelectedDateService.ngOnInit上读取null的属性“0”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58742928/

10-09 09:55