angular - 我无法将数据从服务打印到角度飞镖组件
问题描述
我正在模拟数据,将来将从 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>
解决方案
当当前窗口中发生某些事件(单击、计时器、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()
}
推荐阅读
- flutter - Flutter:StreamBuilder 的行为类似于 StatelessWidget
- ruby-on-rails - Rails:ActiveSupport::MessageEncryptor::InvalidMessage
- msbuild - 如何让 MSBuild 作用于文件夹列表
- java - java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/Workbook 问题
- uwp - UWP + DirectX11:鼠标移动
- terraform - 如何将输出从一个模块传递到另一个模块?
- python - 如何从 Django 中的相关表中获取单个记录?
- ios - 每当应用程序快速出现在屏幕上时如何运行功能?
- google-chrome-extension - 可以更改 Gmail 中的默认(黄色)突出显示颜色吗?
- java - 有两个不相关的罐子的罐子地狱