【发布时间】: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