我正在尝试使用 Angular 构建一个类似于 JQuery 构建器的查询构建器。我面临着发出数据的问题。
当我单击 addGroup、addRule 按钮时,新组将添加到指定级别的数组中。现在我想要整个对象结构,包括被推送的对象结构。如何将其从 HTML 获取到组件?
例如,如果初始结构是:
{
"condition": "AND",
"rules": [
{
"id": "price",
"field": "price",
"type": "double",
"input": "number",
"operator": "less",
"value": 10.25
},
],
"valid": true
}
我现在已经添加了newGroup,所以最新的结构是:
{
"condition": "AND",
"rules": [
{
"id": "price",
"field": "price",
"type": "double",
"input": "number",
"operator": "less",
"value": 10.25
},
{
"condition": "OR",
"rules": [
{
"id": "category",
"field": "category",
"type": "integer",
"input": "select",
"operator": "equal",
"value": 2
},
{
"id": "category",
"field": "category",
"type": "integer",
"input": "select",
"operator": "equal",
"value": 1
}
]
}
],
"valid": true
}
我希望整个对象在 addGroup 方法的组件中可用。可以有
n
数量的嵌套级别,并且我想要整个对象。
工作代码:文字
我们可以使用服务并将整个对象引用存储在服务属性之一中,我们可以从查询构建器中的任何位置访问该属性!
查询.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class QueryService {
entireObject: any;
constructor() {}
}
app.component.ts
...
constructor(private queryService: QueryService) {}
ngOnInit() {
this.queryService.entireObject = this.json;
}
...
规则组.component.ts
...
constructor(private queryService: QueryService) {}
...
...
addGroup(index: number) {
const newGroup = {
condition: 'AND',
rules: [
{
field: 'rule',
operator: 'op',
value: 'value',
},
],
valid: true,
};
if (!this.group.rules) {
this.group.rules = [];
}
this.group.rules.push(newGroup);
// I want to emit the entire object structure not just the one which is added now. How to get the entire top level object from HTML.
console.log(this.queryService.entireObject);
}
...