javascript - 在 JavaScript 中使用 Angular 变量

标签 javascript angular

我已经在 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 变量。 我怎样才能实现这个目标

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

完整的类代码

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

}

最佳答案

Issue

问题出在上下文this上。 this 将指向不同的实例,而不是 NavbarComponent

Fix

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

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

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.

关于javascript - 在 JavaScript 中使用 Angular 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53051267/

相关文章:

javascript - 在调整大小时替换 HTML

javascript - Jasmine.js v2.0.0 - TypeError : Cannot read property 'stopPropagation' of undefined

angular - 如何将自定义类添加到 Angular Material 选项卡?

javascript - 如何使用共享服务将数据从一个组件发送到另一个组件

angular - 将对象放入@NgModule 中的提供者

javascript - Angular 2 - 在使用 "Upgrade Adapter"升级时是否可以使用新路由器

angular - Angular2 的管道如何与数据绑定(bind)一起工作?

javascript - 卡片翻转悬停并单击

javascript - 如何在模块中填充集合以在事件/命令内使用

javascript - jQuery:用变量字符串替换(连接)按钮值