[英]How to pass value of observable from a service to component to update the template
[英]Pass a value from service to component or service to template
我的 Service 方法中有一個 switch case 語句
我的服務.ts
mapGridData(data) {
let colDefObj: GridColumnDef;
const colDefArray = [];
const idToNameMap = {};
let gridDataArray = [];
let aDT: any;
data.attributeMetaData.forEach(subItem => {
if (subItem.isHidden !== 'true') {
switch (subItem.attributeDataType) {
case 'INTEGER':
aDT = 'numeric';
break;
case 'STRING':
aDT = 'text';
break;
case 'DATE':
aDT = 'date';
break;
}
idToNameMap[subItem.attributeId] = subItem.attributeName;
colDefObj = new GridColumnDef(subItem);
colDefArray.push(colDefObj);
}
});
if (data.attributeValues === null) { data.attributeValues = []; }
gridDataArray = data.attributeValues.map(attributeObj => {
const row = { objectId: attributeObj.objectId };
attributeObj.attributeList.forEach(attr => {
row[idToNameMap[attr.attributeId]] = attr.attributeValue;
});
return row;
});
return { gridDataArr: gridDataArray, colDefArr: colDefArray };
}
我在多個組件中使用此服務,如下所示
我的組件.ts
const gridDataObj = this.gridService.mapGridData(data);
在我的組件 html 文件中,我需要綁定 aDT 值,如下所示
<kendo-grid-column *ngFor="let column of gridColDef" [filterable]="column.isFilterable === 'true' ? true : false" [sortable]="column.isSortable === 'true' ? true : false" [locked]="false" filter="{{aDT}}">
那么,如何在組件的模板中綁定服務值呢? 請建議。 謝謝。
如何在組件模板中綁定服務值? 請建議。
要將某些內容與template
綁定,您需要一個組件級別的變量(而不是組件的 function 中的變量,例如let
、 const
、 var
)
在模板中,您使用的是{{aDT}}
即不是任何 object 的一部分,只是普通變量,而不是您應該在組件中聲明它,即public aDT
並在您從服務接收數據時分配一個值。
需要考慮的要點:
正如@Michael D 在評論中指出的那樣,您沒有為服務中的任何 object 分配任何aDT
值,您只是聲明了一個變量,並且每次迭代您只是為其分配了一個新值。
您正在通過服務(即gridDataArray
或colDefArray
。 根據您的要求,如果您想呈現如下內容:
<kendo-grid-column *ngFor="let column of gridColDef" [filterable]="column.isFilterable === 'true' ? true : false" [sortable]="column.isSortable === 'true' ? true : false" [locked]="false" [filter]="column.aDT">
那么它應該是colDefObj
object 的一部分。
service
.
.
let gridDataArray = [];
let aDT: any;
let aDTArray = []; // declare a variable that holds all the values
.
.
.
colDefObj = new GridColumnDef(subItem);
colDefArray.push(colDefObj);
aDTArray.push(aDT); // push your values here
.
.
.
.
return { gridDataArr: gridDataArray, colDefArr: colDefArray, aDT: aDTArray }; // return it here
並在component.ts
public aDT: any[];
public gridDataObj: any ;
const gridDataObj = this.gridService.mapGridData(data);
this.adT = gridDataObj.adtArray ;
this.gridColDef = gridDataObj.colDefArr ;
並在template
中
<kendo-grid-column
*ngFor="let column of gridColDef; let i = index"
[filterable]="column.isFilterable === 'true' ? true : false"
[sortable]="column.isSortable === 'true' ? true : false"
[locked]="false"
[filter]="aDT[i]">
<!-- use on basis of index -->
如果它在某個地方對您有幫助,您應該重新訪問並檢查您的服務,了解如何根據您的需要返回aDT
。
附言
在filter
template
中,而不是filter={{aDT}}
你應該 go for [filter]="aDT"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.