在JavaScript中使用angular变量

时间:2018-10-29 17:57:00

标签: javascript angular

我已经在角类中声明了一个全局变量,例如

public weatherImage: string = "";

现在我在angular类中有了一个javascript方法

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();
  }

但是javascript不允许我使用该weatherImage变量。 我该如何实现

注意:我使用的是使用javascript的ajax请求,而不是由于angular中的CORS问题而导致的角度问题。

完整的班级代码

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();
  }

}

1 个答案:

答案 0 :(得分:2)

  

问题

问题在于上下文thisthis将指向不同的实例,而不是NavbarComponent

  

修复

您可以使用额外的变量NavbarComponent来保留对self的引用。

请参阅以下修改后的代码-

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();
  }
  

注意:您曾在问题中提到过,您正在使用这种方法来避免CORS问题,但是它不能解决您的CORS问题。