Brett Kessler
Brett Kessler

Reputation: 71

New to Angular, getting an error that my variables aren't defined even though they show up?

I'm getting an error in my VScode even though my page seems to be working correctly. I'm guessing that I'm doing something wrong even though things are working.

I'm trying to push objects onto a new array outside of my ngOnInit function, and then use that array in my component with a *ngFor loop. However in my component I get the error "Identifier 'time' is not defined. '' does not contain such a member". On my vars.

I'm assuming it has something to do with the life cycle of events, maybe at the time the information isn't there?

Anyways, here is the code I'm working with:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { WeatherService } from '../weather.service';
import { Subscription } from 'rxjs';
import * as moment from 'moment';
import { _ } from 'underscore';

@Component({
  selector: 'app-forecast',
  templateUrl: './forecast.component.html',
  styleUrls: ['./forecast.component.css']
})
export class ForecastComponent implements OnInit, OnDestroy {

  private weatherSub: Subscription;

  constructor(public weatherService: WeatherService) { }

  daysOfWeek = [];


  ngOnInit() {
    this.weatherSub = this.weatherService.getWeatherListener()
    .subscribe((weather: any) => {
      const daysOfWeekData = weather.weekData.data;
      const slicedDaysOfWeek = daysOfWeekData.slice(1, 6);
      _.each(slicedDaysOfWeek, (day) => {
        const days = moment.unix(day.time).format('dddd');
        day.time = days;
        this.daysOfWeek.push(day);
      });
    });
  }
}

Here is the component code:

<div class="forecast-container">
  <div
  *ngFor="let day of daysOfWeek"
  class="day-container"
  >
    <p>{{day.time}}</p>
    <i class="wi wi-showers"></i>
    <p>{{day.apparentTemperatureHigh}}</p>
    <p>{{day.apparentTemperatureLow}}</p>
  </div>
</div>

As you can see the code is working as I'm getting weather data. However that error scares me. enter image description here

enter image description here

enter image description here

Any suggestions?

Upvotes: 1

Views: 62

Answers (1)

Wilhelmina Lohan
Wilhelmina Lohan

Reputation: 3043

Typescript needs to know the type of the array

public daysOfWeek: any[] = [];

or

interface Day {
  time: string;
  apparentTempertureHight: number;
  apparentTempertureLow: number;
}

then

public daysOfWeek: Day[] = [];

Upvotes: 2

Related Questions