Angular2で作る天気予報チュートリアルver.2

Angular2で天気予報サービス作成する

前回の「Angular2で作る天気予報チュートリアルver.1」の続きからです。前回は環境構築と、静的に都市を入力しその都市の名前から天気予報APIによって天気予報情報を得るところまでしました。

今回の目的

今回は都市の入力フォームから動的にデータを取得し、表示させることをやっていきます。

完成作品

f:id:suga-tech3:20161225171430p:plain

https://drive.google.com/file/d/0BzC949acVHdubU1jbFlpLWdtQmM/view?usp=sharing

完成ソース

github.com

ポイント

-- formを使って都市の天気予報を取得する

  • weather-search.component.ts
<form (ngSubmit)="onSubmit(f)" #f="ngForm">
    <label for="city">City</label>
    <input ngControl="location" type="text" id="city" (input)="onSearchLocation(input.value)" required #input>
    <button type="submit">Add City</button>
</form>
  • ①buttonのsubmitが押された時の処理
  • ②onSearchLocation()で都市の名前を取得する
  • ③ngOnInit()で予測予測変換機能作成する
export class WeatherSearchComponent
{
    private searchStream = new Subject<string>();
    data: any = {};

    // WeatherServiceを使う
    constructor (private _weatherService: WeatherService) {}

    // ①form内のボタンが押された時に天気情報を追加する
    onSubmit(form: ControlGroup) {
        this._weatherService.searchWeatherDate(form.value.location)
            .subscribe(
                data => {
                    const weatherItem = new WeatherItem(data.name, data.weather[0].description, data.main.temp);
                    this._weatherService.addWeatherItem(weatherItem);
                }
            );
    }
    // ②都市の名前を取得する
    onSearchLocation(cityName: string) {
        this.searchStream
            .next(cityName);
    }
    // ③予測変換してくれる機能
    ngOnInit() {
        this.searchStream
            .debounceTime(300)
            .distinctUntilChanged()
            .switchMap((input:string) => this._weatherService.searchWeatherDate(input))
            .subscribe(
                data => this.data = data
            );
    }
}
  • weather.service.ts

-- ①のsubmitが押された時にserviceにてAPIで都市のデータを取得する

searchWeatherDate(cityName: string): Observable<any> {
    return this._http.get('http://api.openweathermap.org/data/2.5/weather?q=' + cityName + '&APPID=任意のID&units=metric')
        .map(response => response.json())
        .catch(error => {
            console.error(error);
            return Observable.throw(error.json())
        });
}

-- ①のsubmitが押された時にserviceにてAPIで都市のデータをpushして追加する

addWeatherItem(weatherItem: WeatherItem) {
    WEATHER_ITEMS.push(weatherItem);
}

追加した都市のデータを取得し表示させる

  • weather-list.component
@Component({
    selector: 'weather-list',
    template: `
        <section class="weather-list">
            <weather-item *ngFor="#weatherItem of weatherItems" [item]="weatherItem"></weather-item>
        </section>
    `,
    directives: [WeatherItemComponent]
})
export class WeatherListComponent implements OnInit {
    weatherItems: WeatherItem[];

    constructor(private _weatherService: WeatherService) {
    }
    // 全天気予報情報を取得する
    ngOnInit():any {
        this.weatherItems = this._weatherService.getWeatherItems();
    }
}

上記でデータを追加する動きをすることができました。 他の機能やサイドバーは完成ソースを見てみてください。

まとめ

チュートリアルすべて終わりです。 componentの概念とAngular2のDIの使い方が複雑でなかなか理解するのに時間がかかった。すべて自分で作るにはなかなかの学習コストが必要になると感じました。