如何将用户输入动态添加到服务中的Http调用
问题描述:
我对Angular非常陌生,并试图与真实数据一起玩。如何将用户输入动态添加到服务中的Http调用
我正在调用darksky API的API,至少我正在尝试做。
我想要做的是;
在开始时我有一个小表格,它要求用户输入一个地方的坐标lat
和long
。
该代码实际上工作正常,如果我预定义lat
和long
并将其作为参数给我的链接。
我创建了一个使API调用的服务。
而我找不到任何可能的方式将我的表单输入值并将其放入 服务。我如何创建它?
我的代码;
我的服务app.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class WeatherService {
constructor (private http: Http) {}
getWeatherCast() {
// If I pre-define lat and long , it works otherwise it says ' lat and long are not known variables :(
return this.http.get('https://api.darksky.net/forecast/ae249dfb82f6c414cde7809cd2c83e6d/'+ lat + ',' + long)
.map((res: Response) => res.json());
}
}
我app.component.ts
import {Component, OnInit} from '@angular/core';
import { WeatherService } from "./app.service" ;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
constructor(private weatherService : WeatherService) {}
ngOnInit() { }
currentWeather ;
test (value: any) {
// console.log(value);
console.log(Number(value.lat), 'lat');
console.log(value.long, 'long');
this.weatherService.getWeatherCast().subscribe(data => this.currentWeather = data);
console.log('Weather is ; ', this.currentWeather);
}
}
和我的HTML;
<div class="container">
<h3> Test Weather application</h3> <br>
<form #myForm ='ngForm' (ngSubmit)="test(myForm.value)">
<div class="form-group">
<label> Lat </label>
<input type="text" class="form-control" name="lat" ngModel>
</div>
<div class="form-group">
<label> Long </label>
<input type="text" class="form-control" name="long" ngModel>
</div>
<button class="btn btn-primary" type="submit">
<h2> Find out What's the weather like ! </h2>
</button>
</form>
</div>
答
定义变量lat和LNG的组件
export class AppComponent implements OnInit{
lat: number;
lng: number;
}
改变内部与模型变量
模板值传递给你的服务,
this.weatherService.getWeatherCast(this.lat,this.lng).subscribe(data => this.currentWeather = data);
而且您的服务应修改为,
getWeatherCast(lat:any,long:any) {
return this.http.get('https://api.darksky.net/forecast/ae249dfb82f6c414cde7809cd2c83e6d/'+ lat + ',' + long)
.map((res: Response) => res.json());
}
为什么这里downvote? – Sajeetharan
非常感谢,它帮助了我很多,我不知道为什么有人对这个问题和你的回答给予了肯定的回答 – Atlas