angular - Angular2 - 使用订阅的 Angular 数据表
问题描述
我正在尝试将Angular数据表与 angular2 一起使用。代码与此类似
myArray: any;
function test() {
callService subscribe((response) => {
this.myArray = response['body'];
})
this.datatableOptions();
}
datatableOptions() {
this.dtOptions = {
order: [1, "desc"],
pagingType: "full_numbers",
pageLength: 100,
lengthMenu: [
[100, 150, 200, -1],
[100, 150, 200, "Todo"]
],
responsive: true,
rowCallback: function(row, data, index) {
var api = this.api();
$('td:eq(0)', row).html(index + (api.page() * api.page.len() + 1));
},
processing: true,
searching: true,
deferRender: true,
data: JSON.parse(JSON.stringify(this.myArray)),
columns: [{
targets: 0,
data: null
},
{
targets: 1,
data: 'A',
defaultContent: '-'
},
{
targets: 2,
data: 'B',
defaultContent: '-'
},
{
targets: 3,
data: 'C',
defaultContent: '-'
},
],
}
}
问题:console.log(response['body'])有数据,但数据表没有显示任何数据。那么,这段代码有什么问题?
解决方案
该函数可能不知道“ this ”。在订阅函数中,“this”是函数的作用域,而不是组件。
你可以用这个技巧来避免它:
myArray: any;
function test() {
let thisContext = this;
callService subscribe((response) => {
thisContext.myArray = response['body'];
})
this.datatableOptions();
}
因此,当您将测试函数输入到 thisContext 变量时,您将“this”范围绑定。在 subscribe 函数中,您使用 thisContext 变量引用该范围。
这样,您应该会找到填充了数据的 myArray 变量。
推荐阅读
- c# - .Net Core 2.2 web api with Entity Framework 和 Linq 不能执行异步任务?
- angular - 如何使用 for 语句使用 Angular 创建 docx 文件?
- python - 如何通过标点符号拆分熊猫中的字符串
- java - 在 Java CLI 应用程序上持久化 Oauth 令牌
- asp.net-mvc - POST 模型中缺少 ASP.Net MVC 下拉列表数据
- python-3.x - 按 id 分组数据帧后执行操作
- html - 将css背景图像添加到R Shiny中的fluidPage sidebarPanel
- r - 网络抓取亚马逊书名
- java - 对象和引用创建
- c# - 运行 WEB API for ASP.NET 框架的进程是什么