简体   繁体   中英

I can't print the data from service to angular dart component

I am mocking up the data and in future this data will be called from an API. Following is the code I have done so far.

Dart model class:

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 service class:

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

Mock up 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();
}

And finally html file:

  <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 will trigger change detection when some events happen in the current window (click, timer, xhr call...)

You can use a timer to 'emulate' and xhr call instead of directly returning you mocking data

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

Or you can manually trigger change detection.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM