【问题标题】:Async function angular service异步函数角度服务
【发布时间】:2021-01-11 14:03:24
【问题描述】:

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);
    }
    

}

问题是,我的组件并没有真正等待我的服务获取数据。我不知道我做错了什么。

提前感谢您的帮助!

【问题讨论】:

    标签: angular promise angular-httpclient


    【解决方案1】:

    JS 是异步的,永远不会等待任何异步调用完成。 所以视图在服务返回数据之前被渲染。 您已经实现了正确的机制,尽管它缺少一些东西。 进行以下更改:

    1. 在服务方法中添加return

      return this.http .get&lt;any[]&gt;(this.url)

    2. 我假设您必须使用 *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

    【讨论】:

    • 您好,我尝试了您所说的并收到以下错误: src/app/ship-list/ship-list.component.ts:25:58 中的错误 - 错误 TS2339:属性“订阅” 'Promise>' 类型不存在。
    【解决方案2】:

    您无需使用额外的承诺:

    getShipList(): Observable<any> {
            this.url = this.url + 'ships';
           return this.http.get<any[]>(this.url);            
        }
    
    ******
    ngOnInit() {
       this.configService.getShipList()
         .subscribe(res => {
            this.shipList = res
          });
        }
    

    【讨论】:

      猜你喜欢
      • 2020-08-23
      • 2016-09-29
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      • 2018-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多