简体   繁体   中英

How to wait for async HTTP requests to return values on Angular 4?

I have some "cards" that I want to get information for them on an Angular service, the problem is that I get this information with http requests on an API, and I want the return to happen after ALL requests are completed.

cards.component.ts

import {Component} from '@angular/core';

import {CardsService} from './cards.service';

import 'easy-pie-chart/dist/jquery.easypiechart.js';

@Component({
  selector: 'cards',
  templateUrl: './cards.html',
  styleUrls: ['./cards.scss']
})
// TODO: move easypiechart to component
export class Cards {

  public charts: any;

  constructor(private _cardsService: CardsService) {
    this.charts = this._cardsService.getData();
  }
}

cards.service.ts

import {Injectable} from '@angular/core';
import {BaThemeConfigProvider, colorHelper} from '../../../theme';
import { Http, Headers, Response } from '@angular/http';
import {Observable} from "rxjs/Observable";

@Injectable()
export class CardsService {
  _meterCountURL = 'http://localhost:8080/meter/count';
  _cardMeter;
  _cardConsumption;
  constructor(private _baConfig:BaThemeConfigProvider, private http: Http) {
  }

  getData() {
    let pieColor = this._baConfig.get().colors.custom.dashboardPieChart;

    let headers = new Headers({'Content-type': 'application/x-www-form-urlencoded',
                               'Authorization': 'Bearer ' + localStorage.getItem('id_token')});

    Observable.forkJoin(
      this.http.get(this._meterCountURL, {headers: headers}).map((response) => {response.json()['data'];}),
      this.http.get(this._meterCountURL, {headers: headers}).map((response) => {response.json()['data'];})
    ).subscribe(
      data => {
        this._cardMeter = data[0];
        this._cardConsumption = data[1];
      },
      error => console.log(error)
    );

    return [
        color: pieColor,
        description: 'Consumo do mês atual',
        stats: 0 || this._cardConsumption,
        icon: 'ion-flash',
      }, {
        color: pieColor,
        description: 'Número de unidades ativas',
        stats: 0 || this._cardMeter,
        icon: 'ion-ios-speedometer',
      }
    ];
  }
}

When It runs, where it should have an Integer, it appears:

[object Object].

If I try to put the return statement INSIDE the subscribe function, 'cards.component.ts' gives me the following error:

Type 'void' is not assignable to type 'Object[]'.

How can I return the card information after the http requests finishes correctly?

You should be returning the observable in your getData() method, then subscribe in your component. This way the component knows when the observable completes (in the subscribe method).

// card.service.ts
getData() {
    return Observable.forkJoin(...);
}

// cards.component.ts
this._cardsService.getData().subscribe(data => {
    this.charts = ...;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM