Home > Back-end >  Show weather info from observable in Angular?
Show weather info from observable in Angular?

Time:04-29

I am trying to simply display weather details in my weather app, but I'm not able to access API response. This is what I tried so far:

API response

In my service.ts

 apiCall(): Observable<any> {
    const rec = new HttpRequest(
      'GET',
      'https://api.openweathermap.org/data/2.5/onecall?lat=41,9109&lon=12'
    );
    return this.http.request(rec);
  } 

In my component.ts

  ngOnInit(): void {
    this.api.apiCall().subscribe((data) => {
      this.response = data.body;
      console.log(this.response)
    });
  }

In my html

      <div>
        <p>{{ response["current"]["humidity"] }}</p>
      </div>

It actually does show the info, but I have to reload the app to make it update, which is not the point of an observable.

CodePudding user response:

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. https://angular.io/api/common/AsyncPipe

CodePudding user response:

How often do you want it to update? When you make an HttpRequest, that is a one-time request and will respond with data once. If you want the page to automatically update, you will need to invoke an http request each time you want a new update (response).

You could use an rxjs timer observable and switchMap each emission to an http request to your api endpoint. That should work.

Edit

Something like this...

In your typescript:

response$ = timer(10000).pipe(switchMap(_ => this._http.get(apiUrl))

In your html:

{{response$ | async | json}}
  • Related