Angular как я могу инициализировать и заполнить массив asyn c и обещать - PullRequest
0 голосов
/ 27 марта 2020

Ниже моего компонента и моего сервиса

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 l oop в моем шаблоне,
Я не знаю, инициализирую ли я массив в компоненте или услуге. Какое лучшее решение?

Обновление

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>

шаблон не показывает параграф "тест" ...... переменная статистика равна нулю, я думаю

Обновление 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; to reports:any[] = [];

и я могу отобразить параграф "test", его возможный массив init со свойством 'value, name and color'?

Обновление 4

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

Ответы [ 2 ]

1 голос
/ 27 марта 2020

Вы пытаетесь сделать синхронный вызов, который, в свою очередь, выполняет асинхронный запрос. Это не будет работать. Когда вы делаете асинхронный вызов где-то в цепочке вызовов, вы должны следовать его правилам. Это не вернет синхронные данные, однако вы пытаетесь.

С другой стороны, вы можете отобразить ответ асинхронного вызова в массив вашего формата. Но для извлечения этого массива вам все равно нужно придерживаться правил асинхронного запроса.

Попробуйте следующее

Сервис

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>
0 голосов
/ 27 марта 2020

если я использую это, я могу видеть в журнале возвращение объекта, но почему шаблон не работает для l oop в списке массивов?

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...