2017-08-13 9 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

モデル変数

であなたのテンプレートがあなたのサービスに値を渡し、コンポーネント

export class AppComponent implements OnInit{ 
lat: number; 
lng: number; 
} 

の変化内部変数は、緯度とLNGの定義

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

関連する問題