wait for asynchronous functions to finish in Angular 我的组件“ ship-list”想要从后端服务器获取列表。所以,我做了一个服务 (config.service.ts)
import { Injectable, OnInit } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ConfigService {
url = 'http://192.168.1.26:8080/';
constructor(private http:HttpClient) { }
async getShipList() {
this.url = this.url + 'ships';
this.http
.get<any[]>(this.url)
.subscribe(
(response) => {
console.log("Response : ", response);
return (response);
},
(error) => {
console.log("Error ! : " + error);
}
);
}
}
然后,在我的组件中的ngOnInit中,我调用此函数并等待结果:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { faCartArrowDown } from '@fortawesome/free-solid-svg-icons';
import { faChartArea } from '@fortawesome/free-solid-svg-icons';
// Services :
import { ConfigService } from '../config/config.service';
@Component({
selector: 'app-ship-list',
templateUrl: './ship-list.component.html',
styleUrls: ['./ship-list.component.scss']
})
export class ShipListComponent implements OnInit {
// Icons
faChartArea = faChartArea;
faCartArrowDown = faCartArrowDown;
// Var
searchText: any;
shipList: any;
url = this.configService.url;
constructor(private http:HttpClient, private configService: ConfigService) { }
async ngOnInit() {
this.shipList = await this.configService.getShipList();
console.log(this.shipList);
}
}
问题是,我的组件并没有真正等待我的服务获取数据。我找不到我做错了什么。
提前感谢您的帮助!
答案 0 :(得分:0)
JS是异步的,并且永远不会等待任何异步调用完成。 因此,在服务返回数据之前先渲染视图。 您已经实现了正确的机制,尽管它缺少一些东西。 做以下更改:
在服务方法中添加return
:
return this.http .get<any[]>(this.url)
我假设您必须使用*ngFor
呈现列表,所以初始化*ngFor
使用的数组始终是一个好习惯:
shipList: any[] = [];
整个代码:
async ngOnInit() {
this.shipList = await this.configService.getShipList().subscribe((result)=>{
this.shipList = result
})
}
服务:
getShipList() {
this.url = this.url;
return this.http
.get<any[]>(this.url)
}
这是示例:demo
答案 1 :(得分:-1)
您无需使用其他承诺:
getShipList(): Observable<any> {
this.url = this.url + 'ships';
return this.http.get<any[]>(this.url);
}
******
ngOnInit() {
this.configService.getShipList()
.subscribe(res => {
this.shipList = res
});
}