[英]Async function angular service
等待异步函数在 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); } }
问题是,我的组件并没有真正等待我的服务获取数据。 我无法找出我做错了什么。
预先感谢您的帮助 !
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)
}
这是示例: 演示
您无需使用额外的承诺:
getShipList(): Observable<any> {
this.url = this.url + 'ships';
return this.http.get<any[]>(this.url);
}
******
ngOnInit() {
this.configService.getShipList()
.subscribe(res => {
this.shipList = res
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.