首页 > 解决方案 > 我的 Angular 应用程序在本地工作,但在 Heroku 上出现错误。源地图网址:index.js.map

问题描述

我可以在本地(使用 ng serve 时)从 JSON 中提取数据并用它修改 DOM,但不能在 Heroku 上。

快速第二个问题:为什么 dry_da 向 DOM 返回一个 NaN 值,但 console.log 中完全相同的代码(component.ts 的最后一行)打印一个数字?

这是 Heroku 上的网站:https ://densityaltitude.herokuapp.com/

这是错误:

源地图错误:错误:JSON.parse:JSON 数据第 1 行第 1 列的意外字符资源 URL:https ://densityaltitude.herokuapp.com/main-es2015.b2df828509b484a6cc02.js 源地图 URL:index.js.map

这是我从中提取的 JSON 示例:

https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22

这是我的dailyda.component.html:

<div *ngIf = "weather"> <!-- *ngIf prevents errors, because of the 
delay in retrieving JSON from the API. Once weather has a value, this 
div is displayed.-->
    <p>Temp in Kelvins: {{ temp }}</p> 
    <p>Static Atmos. Pressure in hectopascals: {{ press }}</p>
    <p> Density Altitude (assumes dry air): {{dry_da}} </p>
</div>

组件.ts:

import { Component, OnInit } from '@angular/core';
import { WeatherdataService } from '../services/weatherdata.service';
import { THIS_EXPR } from '@angular/compiler/src/output/output_ast';
@Component({
  selector: 'app-dailyda',
  templateUrl: './dailyda.component.html',
  styleUrls: ['./dailyda.component.scss']
})
export class DailydaComponent implements OnInit {
  weather;
  temp;
  press;
  //Crunch your numbers here, store it in a variable called result, etc.,
  //And in the template, {{ result }} will display that number.
  ISAT = 288.15;
  ISAP = 29.92;
  lapse_rate = 0.0065;
  R = 8.3144598;
  g = 9.80665;
  M = 0.028964; // This is the molar mass of DRY air.
  dry_da = this.ISAT/this.temp *(1 - ((this.press/this.ISAP)/(this.temp/this.ISAT))** ((this.lapse_rate*this.R)/(this.g*this.M - this.lapse_rate*this.R)))



  constructor(private weatherdataService: WeatherdataService) { }

  ngOnInit() {
    this.weatherdataService.getWeather().subscribe((data)=>{
      console.log(data);
      this.weather = data;
      this.temp = this.weather.main.temp;
      this.press = this.weather.main.pressure;
      console.log(this.ISAT/this.temp *(1 - ((this.press/this.ISAP)/(this.temp/this.ISAT))** ((this.lapse_rate*this.R)/(this.g*this.M - this.lapse_rate*this.R))))
    }
    )};

};

标签: javascriptangularheroku

解决方案


您的问题是(DailydaComponent)中的这一行:

this.temp = this.weather.main.temp;

您在 HTML 模板中使用 *ngIf 阻止了访问。但是在您的组件构造函数中,您可以在其中包含某些内容之前访问它。像这样:

constructor(weatherdataService) {
    this.weatherdataService = weatherdataService;
    this.temp = this.weather.main.temp;
    this.press = this.weather.main.temp;

移动这些行:

    this.temp = this.weather.main.temp;
    this.press = this.weather.main.temp;

在您的订阅发出一个值之后,在您的 ngOnInit 函数中。在这一行之后:

this.weather = data;

推荐阅读