2017-08-13 16 views
0

我對Angular非常陌生,並試圖與真實數據一起玩。如何將用戶輸入動態添加到服務中的Http調用

我正在調用darksky API的API,至少我正在嘗試做。

我想要做的是;

在開始時我有一個小表格,它要求用戶輸入一個地方的座標latlong

該代碼實際上工作正常,如果我預定義latlong並將其作爲參數給我的鏈接。

我創建了一個使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> 

回答

0

定義變量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()); 
     } 
+0

爲什麼這裏downvote? – Sajeetharan

+0

非常感謝,它幫助了我很多,我不知道爲什麼有人對這個問題和你的回答給予了肯定的回答 – Atlas

相關問題