如何使用promise和HttpClient

时间:2018-04-06 10:16:36

标签: angular api es6-promise

我最近开始使用Angular和Ionic,我试图做一个简单的应用程序,在某些时候我希望它使用天气API(我选择openweathermap)。所以这就是我试图做的事情:

我创建了一个名为meteo.provider.ts的提供程序:

import { Injectable } from '@angular/core';
import {Meteo, Weather} from "../model-class/model-class";
import { HttpClient} from "@angular/common/http";
import {Observable} from "rxjs/Observable";
import 'rxjs/add/operator/map'

@Injectable()
export class MeteoProvider {

//Meteo url
private meteoServiceUrl = 'http://api.openweathermap.org/data/2.5/weather?id=6455645&units=metric&appid=mykey';

constructor(public http: HttpClient) {
    console.log('Hello MeteoProvider Provider');
}

getMeteo():Promise<Meteo> {
    return this.http.get(this.meteoServiceUrl).toPromise()
        .then(data => { this.Meteo = data});
}
}

我尝试在weather API

上为元素创建一个模态类
    export class Meteo {
        coord: Coord;
        weather: Weather;
        main: Main;
        id: number;
        name: string;
    }

    export class Coord {
       lat: number;
       lon: number;
    }

    export class Weather {
       id: number;
       main: string;
       description: string;
       icon: string;
    }

    export class Main {
       temp : number;
       pressure: number;
       humidity: number;
    }

以下是我尝试在home.ts

中调用它的方法
    import { Component } from '@angular/core';
    import {NavController, NavParams} from 'ionic-angular';
    import {BateauPage} from "../bateau/bateau";
    import {MuseePage} from "../musee/musee";
    import {MeteoPage} from "../meteo/meteo";
    import {TemoignagePage} from "../temoignage/temoignage";
    import {MeteoProvider} from "../../providers/meteo/meteo.provider";
    import {Meteo} from "../../providers/model-class/model-class";

    @Component({
      selector: 'page-home',
      templateUrl: 'home.html'
    })
    export class HomePage {
        meteo: Meteo;
        constructor(public navCtrl: NavController, public navParams: NavParams, public meteoProvider: MeteoProvider) {

        }

      ngOnInit() {
     /* this.meteoProvider.getMeteo().subscribe(meteo=>{
      console.log(this.meteo);
      });*/

    }

我收到错误,所以我知道我的方法不正确,但我不确定我是否理解这个过程。也许我并没有完全了解诺言是如何运作的。

我不确定如何呈现它,因为当我搜索时,我会看到一些不同的方法来调用API,但不知怎的,我设法不让它们工作。

2 个答案:

答案 0 :(得分:0)

问题在于您将ObservablesPromises混合在一起。坚持观察。您从服务返回Promise,然后尝试在组件中订阅它。您subscribe可观察到,then承诺。

service.ts

getMeteo(): Observable<Meteo> {
    return this.http.get(this.meteoServiceUrl);
}

component.ts

ngOnInit() {
 this.meteoProvider.getMeteo().subscribe(meteo =>{
   this.meteo = meteo;
  });
}

答案 1 :(得分:0)

您可以在提供商中进行交换

getMeteo():Promise<Meteo> {
return this.http.get(this.meteoServiceUrl).toPromise()
    .then(data => { this.Meteo = data});

}

通过

getMeteo(){
return this.http.get(this.meteoServiceUrl);

}

然后您可以在home.ts direct

订阅getMeteo()