【问题标题】:I can't print the data from service to angular dart component我无法将数据从服务打印到角度飞镖组件
【发布时间】:2020-08-16 10:06:11
【问题描述】:

我正在模拟数据,将来会从 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';
}

Dart 服务类:

@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>

【问题讨论】:

    标签: angular dart service


    【解决方案1】:

    当当前窗口中发生某些事件(点击、计时器、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()
    }
    

    【讨论】:

      猜你喜欢
      • 2017-11-26
      • 2018-07-08
      • 1970-01-01
      • 1970-01-01
      • 2014-06-26
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多