首页 > 解决方案 > 在javascript中使用角度变量

问题描述

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

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变量。我怎么能做到这一点

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

完整的类代码

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

}

标签: javascriptangular

解决方案


问题

问题在于上下文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 问题。


推荐阅读