【问题标题】:How do I return a Promise and get the data from it? [duplicate]如何返回 Promise 并从中获取数据? [复制]
【发布时间】:2022-01-10 06:56:06
【问题描述】:

我无法创建一个函数来返回我想使用 Promise 使用的数据“数组”。 我使用的技术栈是 Angular、Typescript 和 Express.js。我可以让数据在 getData() 函数内部返回,但是,数据没有在 return 语句中传递,我只是在 ngOnInit() 中得到一个空数组;

getData函数:

public async getData(user: any): Promise<any> {

        this._url = 'http://localhost:5000/account/data';

        const data = this._http.post<any>(this._url, user).toPromise();

        return data

 
    }

ngOnInit:

ngOnInit(): void {

    this._account.getData(this.login)
    .then((data: any) => {
      console.log(data)
    });

  }

result = [ ]; 

【问题讨论】:

    标签: angular typescript express promise


    【解决方案1】:

    试试这个(只是将 await 添加到您的 http 调用中):

    public async getData(user: any): Promise {
    
        this._url = 'http://localhost:5000/account/data';
    
        const data = await this._http.post<any>(this._url, user).toPromise();
    
        return data
    }
    
    ngOnInit(): void {
       this._account.getData(this.login)
       .then((data: any) => {
          console.log(data)
       });
    }
    

    EXTRA:使用 angular http 模块的更好方法是 OBSERVABLE 方式:

    import { Observable } from 'rxjs';
    
    
    public getData(user: any): Observable<any> {
        this._url = 'http://localhost:5000/account/data';
        return this._http.post<any>(this._url, user);
    }
    
    ngOnInit(): void {
       this._account.getData(this.login)
       .subscribe((data: any) => {
          console.log(data)
       });
    }
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 2017-09-05
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 2018-04-07
      相关资源
      最近更新 更多