角度4:尝试使用表单数据来格式化服务中的字符串,但是页面不断重载,变量未重新分配表单值

问题描述 投票:0回答:1

[基本上,我想采用邮政编码的形式,格式化URL,对该URL进行API调用,然后将数据从JSON打印到屏幕。

我已经在格式化网址并获取所需的数据。问题是我无法将表单数据存储在变量中,无法使用它来格式化我的URL。

这里是component.ts:

import { WeatherdataService } from '../services/weatherdata.service';
import { THIS_EXPR } from '@angular/compiler/src/output/output_ast';
import { FormControl,FormGroup } from '@angular/forms';
@Component({
  selector: 'app-dailyda',
  templateUrl: './dailyda.component.html',
  styleUrls: ['./dailyda.component.scss']
})
export class DailydaComponent implements OnInit {

  zipForm = new FormGroup({
    zipCode:new FormControl('37064') //Default value in quotes
  })
  zipcode = 60610;
  onSubmit() {
    this.zipcode = this.zipForm.value.zipCode;
    console.log(this.zipcode);
  }
  weather;
  temp;
  press;
  dry_da;
  //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 = 1013.25;
  expon = 0.234978134;
  // lapse_rate = 0.0065;
  // R = 8.3144598; Replaced all this with expon
  // g = 9.80665;
  // M = 0.028964; // This is the molar mass of DRY air.



  constructor(private weatherdataService: WeatherdataService) { }

  ngOnInit() {
    this.weatherdataService.getWeather(this.zipcode).subscribe((data)=>{
       // add zip code to .getWeather call
      this.weather = data;
      this.temp = this.weather.main.temp;
      this.press = this.weather.main.pressure;
      this.dry_da = Math.round(3.28084 * this.ISAT/0.0065 *(1 - ((this.press/this.ISAP)/(this.temp/this.ISAT))** (this.expon)));
    }
    )};

};

这里是compnonent.html:(我尝试使用ngSubmit(),但“提交”按钮重新加载了我的页面,但没有任何显示。

    <label>
        Zip Code:
        <input type="text" [formControl]='zipCode'>
    </label>
    <button type="button" (click)="onSubmit()">Submit</button>
</form>
<div *ngIf = 'zipForm'>
    <p>Current Zip: {{ zipCode.value }}</p>
</div>
<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.-->
    <h4> Density Altitude (assumes dry air): </h4>
    <h2><strong>{{ dry_da }} ft</strong></h2>
    <h4> Temp in Kelvins: </h4>
    <h2><strong>{{ temp }}</strong></h2>
    <h4> Static Atmospheric Pressure in hPa: </h4>
    <h2><strong>{{ press }}</strong></h2>
</div>

这里是service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class WeatherdataService {
  API_KEY = 'a641de02f55d14465d55e5fd6edb7506';

  constructor(private httpClient: HttpClient) { }

  public getWeather(zipcode){ // getWeather(zipcode)
    return this.httpClient.get(
`https://api.openweathermap.org/data/2.5/weather?zip=${zipcode}&appid=${this.API_KEY}` 
);  // where to format with zip code
  }
}



javascript html angular dom
1个回答
1
投票
this.zipcode = this.zipForm.get('zipCode').value;
© www.soinside.com 2019 - 2024. All rights reserved.