0

I am creating a weather app. My service made a call to the api and mapped the data to a global parameter. My component then accesses the global parameter and modifies the data to the correct format I need through a function.

The problem I am having is for some reason the function is mutating the original data.

As a work around I can create a new time property in my component parameter and the function won't modify the original data. But if I name the component property to time the original service data gets mutated.

Why is it doing this? Did I miss something?

Original mapped service data:

dailyForecast = [
0: {time: 1547618400}
1: {time: 1547704800}
2: {time: 1547791200}
];

weather.service.ts

@Injectable({
  providedIn: 'root'
})
export class WeatherService {

  // Weather parameters
  public dailyForecast: any;

  private weatherUrl = 'http://localhost:3000/weather/data';

  constructor(private http: HttpClient) {
  }

  getWeather(location) {
    return this.http.post(this.weatherUrl, location, httpOptions)
      .pipe(
        map((data: any) => {
          this.dailyForecast = data.daily;

          return data.currently;
        })
      );
  }

}

daily.component.ts

export class DailyComponent implements OnInit {

  dailyForecast: any;

  constructor(public weather: WeatherService) {
    this.dailyForecast = this.weather.dailyForecast.data;
  }

  ngOnInit() {
    this.convertUnixTime();
  }

  convertUnixTime() {
    console.log(this.weather.dailyForecast.data[0].time + ": original before loop")

    for(let i=0; i < this.dailyForecast.length; i++) {
      this.dailyForecast[i].time = this.weather.dailyForecast.data[i].time * 1000;

    console.log(this.weather.dailyForecast.data[0].time + ": original after loop")
    console.log(this.dailyForecast[0].time + ": component")
  }

console log printout

1547618400: original before loop
1547618400000: original after loop
1547618400000: component

If you notice the original number before and after the loop are different because for some reason the function is being applied to the original data.

If I however, change the function to create a new property called timeConverted:

for(let i=0; i < this.dailyForecast.length; i++) {
          this.dailyForecast[i].timeConverted = this.weather.dailyForecast.data[i].time * 1000;

the output is correct

1547618400: original before loop
1547618400: original after loop
1547618400000: component

What gives? Just trying to understand what is going on.

Cuong Vo
  • 249
  • 1
  • 6
  • 16

0 Answers0