首页 > 解决方案 > 我无法将数据从服务打印到角度飞镖组件

问题描述

我正在模拟数据,将来将从 API 调用这些数据。以下是我到目前为止所做的代码。

飞镖模型类:

class Main {
  final int id;
  String date;
  String orderID;
  String customer;
  String answeredBy;
  String requestType;

  Main(this.id, this.date, this.orderID, this.customer,
       this.answeredBy, this.requestType);

  @override
  String toString() =>
      '$id: $date: $orderID: $customer: $answeredBy: $requestType';
}

飞镖服务类:

@Injectable()
class MainService {
 Future<List<Main>> getAll() async => main_mock_data;
}

模拟数据:

import 'main.dart';

final main_mock_data = <Main>[
 Main(1, '12-1-2020', 'orderID', 'customer', 'answeredBy', 'requestType'),
];

app_component.dart

@Component(
    selector: 'app-main',
    styleUrls: ['main_component.css'],
    templateUrl: 'main_component.html',
    providers: [ClassProvider(MainService)])

class MainComponent implements OnInit {
     final MainService _mainService; // defining private property
    
     List<Main> data;
     Main selected;
    
     MainComponent(this._mainService);
    
     Future<void> _getTableData() async {
         data = await _mainService.getAll();
     }
    
     void ngOnInit() => _getTableData();
}

最后是 html 文件:

  <tbody>
   <tr *ngFor="let item of data">
    <td>{{item.Date}}</td>
    <td>{{item.OrderID}}</td>
    <td>{{item.Customer}}</td>
    <td>{{item.AnsweredBy}}</td>
    <td>{{item.RequestType}}</td>
   </tr>
  </tbody>

标签: angulardartservice

解决方案


当当前窗口中发生某些事件(单击、计时器、xhr 调用...)时,Angular 将触发更改检测

您可以使用计时器来“模拟”和 xhr 调用,而不是直接返回模拟数据

Future<List<Main>> getAll() {
  return Future.delayed(
    Duration(milliseconds: 500),
    () => main_mock_data,
  );
}

或者您可以手动触发更改检测。

final ChangeDetectorRef changeDetection;
MainComponent(this._mainService, this.changeDetection);

Future<void> _getTableData() async {
  data = await _mainService.getAll();
  changeDetection.markForCheck()
}

推荐阅读