【问题标题】:Angular how i can initialize and populate array with async and promiseAngular 我如何用异步和承诺初始化和填充数组
【发布时间】:2020-07-08 01:28:26
【问题描述】:

在我的组件和我的服务之下

report.component.html


<div *ngFor="let report of reports">
        <p>{{report.name}}</p>
        <p>{{report.value}}</p>
        <p>{{report.color}}</p>
</div>

report.component.ts

export class ReportComponent implements OnInit{

reports = this.reportService.getLists('2020-03-20', '2020-03-26');

constructor(private reportService: ReportService) {}

ngOnInit(){}
}

report.service.ts

export class ReportService {


async getLists(startDate: string, endDate: string) {
    this.getReport('2020-03-20', '2020-03-26').then(response => {
      let lists = [
    {
        name: 'Opens',
        value: response .opens, //2
        color: 'green',
      },
        {
        name: 'Closes',
        value: response .opens, //1
        color: 'red',
      }];
      return lists;
    });
  }

 async getReport(startDate: string, endDate: string) {
    return await this.http
      .get<Report>(
       `https://localhost:44354/report?startDate=${startDate}&endDate=${endDate}`,
        this.httpOptions
      )
      .toPromise();
  }
 }


可以初始化和填充数组列表吗?

我想在我的模板中使用 ngFor 循环,
我不知道我是在组件还是服务中初始化数组。什么是最好的解决方案?

更新

export class ReportComponent implements OnInit {
  reports: any;

  constructor(private reportService: ReportService) { }

  ngOnInit() {
    // you still need to subscribe to obtain the result
    this.reportService.getLists('2020-03-20', '2020-03-26').subscribe(  
      response => { 
           this.reports = response;  
           console.log(this.reports);  
    });
  }
}

我测试了你的答案,但它不起作用, 我只是尝试用值初始化我的数组,我的模板上有结果

所以我认为,init 数组不好..

我只想用报表对象从数组 List 中初始化属性值 例如 this.list[0].value = report.opens 我不知道它是否清楚......

输出

(2) […]
    0: {…}
        name:"Opens"
        value: 2
        color:"green"
        <prototype>: Object { … }
    1: {…}
        name:"Closes"
        value: 1
        color: "red"
        <prototype>: Object { … }
    ​length: 2
    ​<prototype>: Array []

组件中的console.log(this.report)上方。

更新 2

<ng-container *ngIf="reports">
  <p>test</p>
  <div *ngFor="let report of reports">
    <p>{{report.name}}</p>
    <p>{{report.value}}</p>
    <p>{{report.color}}</p>
  </div>
</ng-container>

模板没有显示段落“测试”......我认为变量 stats 为空

更新 3

report.component.html

<ng-container *ngIf="reports">
  <p>test</p>
  <div *ngFor="let report of reports">
    <p>{{report.name}}</p>
    <p>{{report.value}}</p>
    <p>{{report.color}}</p>
  </div>
</ng-container>

report.component.ts

export class SmtpComponent implements OnInit, AfterViewInit, OnDestroy {
reports:any[] = [];
}

我把reports: any;改成reports:any[] = [];

我可以显示段落“测试”, 它可能具有属性“值、名称和颜色”的初始化数组?

更新 4

    this.reportService.getReport('2020-03-20', '2020-03-26').subscribe(
      response => { this.lists= response;   this._cdr.detectChanges()},
      error => { console.log("Error")}
    );

【问题讨论】:

  • 请更具体。你想在哪里初始化和填充数组?以及出于什么目的?问题是在 ngFor 指令中使用报告作为数组?

标签: javascript angular typescript asynchronous promise


【解决方案1】:

您正在尝试进行同步调用,而该调用又会发出异步请求。这是行不通的。当您在调用链中的某处进行异步调用时,您需要遵循它的规则。无论您尝试如何,它都不会返回同步数据。

另一方面,您可以将异步调用的响应映射到您的格式数组。但是要检索这个数组,你仍然需要遵守异步请求的规则。

试试下面的

服务

export class ReportService {
  public getReport(startDate: string, endDate: string): Observable<any> {
    return this.http.get(`https://localhost:44354/report?startDate=${startDate}&endDate=${endDate}`, this.httpOptions)
      .pipe(map(response => {
        return 
        [
          { name: 'Opens', value: response.opens, color: 'green' },
          { name: 'Opens', value: response.opens, color: 'green' }
        ]
      }));
  }
}

控制器

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';

export class ReportComponent implements OnInit {
  reports: any

  constructor(private reportService: ReportService, private _cdr: ChangeDetectorRef) { }

  ngOnInit() {
    // you still need to subscribe to obtain the result
    this.reportService.getLists('2020-03-20', '2020-03-26').subscribe(  
      response => { this.reports = response },
      error => { // handle error }
    );
    this._cdr.detectChanges();
  }
}

更新

您也可以在渲染数据之前进行检查。

<ng-container *ngIf="reports">
  <div *ngFor="let report of reports">
    <p>{{report.name}}</p>
    <p>{{report.value}}</p>
    <p>{{report.color}}</p>
  </div>
</ng-container>

【讨论】:

  • @Micheal D,感谢您的帮助,我的组件从服务中获取值,但是为什么模板不显示值?
  • @Micheal D,我使用你的代码,我更新了问题。
  • @Heptagram:您能否将 console.log() 的输出发布到问题中?
  • @Heptagram:请删除组件中的初始化reports,运行代码并发布控制台日志。做reports: any
  • @Micheal D,输出是白衣报告:任何。
【解决方案2】:

如果我使用这个,我可以在日志中看到对象返回,但是为什么模板不能在数组列表上循环?

export class ReportComponent implements OnInit {
  reports: any

  constructor(private reportService: ReportService) { }

  ngOnInit() {
    // you still need to subscribe to obtain the result
    this.reportService.getLists('2020-03-20', '2020-03-26').subscribe(  
      response => { 
           this.reports = response;  
           console.log(this.reports);  
    });
  }
}

【讨论】:

  • 您应该发布问题的任何更新。不作为答案。我也更新了我的答案。请检查它是否有效
  • 对不起,我从 StackOverFlow 开始
猜你喜欢
  • 1970-01-01
  • 2013-01-18
  • 2014-10-04
  • 2017-01-04
  • 2018-07-01
  • 2018-09-07
  • 2018-01-31
  • 1970-01-01
  • 2015-10-09
相关资源
最近更新 更多