Как спроектировать услугу http запроса?Что я делаю неправильно? - PullRequest
0 голосов
/ 02 марта 2019

Я хочу спросить, что кто-то считает наилучшей реализацией того, чего я хочу достичь.

Я хочу получать данные из HTTP-запроса при инициализации компонента и обрабатывать данные одновременно.Данные поступят от службы, которая будет выполнять запрос HttpClient.get().

Компонент:

import {AfterViewInit, Component, OnInit} from '@angular/core';
import {HttpHandleService} from '../services/http-handle.service';

@Component({
    selector: 'app-http-displayer',
    templateUrl: './http-displayer.component.html',
    styleUrls: ['./http-displayer.component.css']
})
export class HttpDisplayerComponent implements OnInit, AfterViewInit {
    public data: any = [];

    constructor(private httpHandleService: HttpHandleService) {
    }

    ngOnInit() {
        this.httpHandleService.getData().subscribe((recivedData) => this.data = recivedData); // get the data 
        doSomthing(this.data); // want to process the data here, but still data is empty array
    }

    ngAfterViewInit(): void {
        doSomething(this.data);  // want to process the data here, but still, data is an empty array
        // What I was thinking is that by the time this lifecycle hook will be activated this.data will be assigned with the received data.
    }
}

Служба:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient} from '@angular/common/http';

@Injectable({
    providedIn: 'root'
})
export class HttpHandleService {

    constructor(private http: HttpClient) {
    }

    getData(): Observable<any> {
        return this.http.get('https://reqres.in/api/users?page=2');
    }
}

1 Ответ

0 голосов
/ 02 марта 2019

Наблюдаемые являются асинхронными .

this.httpHandleService.getData().subscribe((receivedData) => { 
  this.data = receivedData;
  this.doSomething(this.data); // accessed here
});

Существует множество руководств о том, что такое наблюдаемая и как она работает.Angular имеет несколько: https://angular.io/guide/rx-library

...