【问题标题】:How to design http request service? What am I doing wrong?如何设计http请求服务?我究竟做错了什么?
【发布时间】:2019-07-24 11:42:58
【问题描述】:

我想询问任何人认为什么是我想要实现的最佳实现。

我想在组件初始化时从 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');
    }
}

【问题讨论】:

  • 您可以在订阅块内处理收到的数据。
  • 请阅读一般的异步 JavaScript 和具体的 observables - 如果你想在你的组件中使用这个值,你必须处理它不会立即可用的事实。

标签: angular typescript rxjs httprequest httpclient


【解决方案1】:

Observables 是异步的。

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

关于什么是 observable 以及它是如何工作的,有很多很多指南。 Angular 有几个:https://angular.io/guide/rx-library

【讨论】:

    猜你喜欢
    • 2013-08-06
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    • 2019-12-23
    • 2014-06-15
    相关资源
    最近更新 更多