Chris Hadfield
Chris Hadfield

Reputation: 524

use angular variable inside javascript

I have declared a global variable in angular class like

public weatherImage: string = "";

Now I have a javascript method inside angular class

public getWeather(city: string) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
      if (this.readyState === 4 && this.status === 200) {
        var weatherImage = "https:" + JSON.parse(this.responseText)['current']['condition']['icon'];
        var weather = JSON.parse(this.responseText)['current']['condition']['text'];
        var temperature = JSON.parse(this.responseText)['current']['temp_c'];

        //this.weatherImage = weatherImage;
        console.log(weatherImage);
        console.log(weather);
        console.log(temperature);
      }
    };
    xhttp.open("get", "https://api.apixu.com/v1/current.json?key=533920d31cc44af491660306182603&q="+city, true);
    xhttp.send();
  }

but javascript doesn't let me use that weatherImage variable. How I can achieve this

Note: I have use ajax request using javascript rather than angular due CORS issue in angular.

Full class code

import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

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

  public navbarOpen = false;
  public language: string = "";
  private transData: string[] = [];
  public weatherImage: string = "";
  public temparature: string = "";
  public city: string = "";
  public weather: string = "";
  private cities: string[] = ["", "", "", ""];

  constructor(
    private translate: TranslateService
  ) { }

  ngOnInit() {
    if (localStorage.getItem('pcLang') == "en") {
      this.language = "Eng";
      this.translate.use("en");
    } else {
      this.language = "नेपाली";
      this.translate.use("ne");
    }

    this.getWeather("Kathmandu");
  }

  public getWeather(city: string) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
      if (this.readyState === 4 && this.status === 200) {
        var weatherImage = "https:" + JSON.parse(this.responseText)['current']['condition']['icon'];
        var weather = JSON.parse(this.responseText)['current']['condition']['text'];
        var temperature = JSON.parse(this.responseText)['current']['temp_c'];

       weatherImage = weatherImage;
        console.log(weatherImage);
        console.log(weather);
        console.log(temperature);
      }
    };
    xhttp.open("get", "https://api.apixu.com/v1/current.json?key=533920d31cc44af491660306182603&q="+city, true);
    xhttp.send();
  }

  toggleNavbar() {
    this.navbarOpen = !this.navbarOpen;
  }

  public changeLanguage() {
    if (this.language == "Eng") {
      this.language = "नेपाली";
      this.setLanguage("ne");
    } else {
      this.language = "Eng";
      this.setLanguage("en");
    }
  }

  private getTranslation() {
    this.translate.get(['ARE_YOU_SURE', 'YES_LOGOUT', 'CANCEL']).subscribe(
      (result: [string]) => {
        this.transData = result;
      }
    );
  }

  private setLanguage(lang): void {
    this.translate.use(lang);
    localStorage.setItem('pcLang', lang);
    this.getTranslation();
  }

}

Upvotes: 0

Views: 94

Answers (1)

Sunil
Sunil

Reputation: 11243

Issue

The issue is with context this. this will point to different instance rather than NavbarComponent.

Fix

You can keep the reference of NavbarComponent by using extra variable self.

See the following modified code -

public getWeather(city: string) {
    var self = this; //<----keep the current context
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
      if (this.readyState === 4 && this.status === 200) {
        var weatherImage = "https:" + JSON.parse(this.responseText)['current']['condition']['icon'];
        var weather = JSON.parse(this.responseText)['current']['condition']['text'];
        var temperature = JSON.parse(this.responseText)['current']['temp_c'];

        self.weatherImage = weatherImage; //<-- self is used here.
        console.log(weatherImage);
        console.log(weather);
        console.log(temperature);
      }
    };
    xhttp.open("get", "https://api.apixu.com/v1/current.json?key=533920d31cc44af491660306182603&q="+city, true);
    xhttp.send();
  }

Note : You had mentioned in your question you are using this approach to avoid CORS issue however it will not fix your CORS issue.

Upvotes: 2

Related Questions