第一步是您需要编写一个后端函数或(API),该后端函数应该以@987654321所示的相同结构(层次结构)返回数据@,我说树中的每个节点都是elem对象,每个elem对象都有属性id, name, children:Item[]
该函数必须返回一个项目数组Item[]。
所以函数原型是:
<Item[]> getMyTreeData(){
// 1- Fetch the tree data from the DB.
// 2- Convert your data to the appropirate structure accepted by angular material
// 3- return the data
}
// I wrote the algorithm to convert your data in typescript, you need to use the syntax of your backend programming langauge
// you should be fine with that
let tree_data: any = []; // this will be array of objects
// collect all the descriptions and names nodes form the data array
let descrptions: any = [];
let names:any = [];
Scenarios.forEach(elem => { // Scenarios are the data array you posted in yout question
let description_node: any = {
name: elem.description
}
descrptions.push(description_node);
let name_node: any = {
name: elem.name
}
names.push(name_node);
});
let root_obj: any = {
name: 'Scenarios ',
children: [
{ name: 'Description' , children: descrptions},
{ name: 'Name ' , children: names},
]
};
tree_data.push(root_obj);
// then you need to convert the root_obj to JSON format according to your programing language
// that's it..
// the result of printing the root_obj should be:
[
{
name: 'Scenarios',
children: [
{ name: 'Description' , children: [
{name: 'Description1'},
{name: 'Description2'},
{name: 'Description3'},
]},
{ name: 'Name' , children: [
{name: 'Name1'},
{name: 'Name2'},
{name: 'Name3'},
]},
];
}
]
第二步是使用get http请求和服务从Angular应用程序调用您之前在Step1中编写的函数(API)。你会发现很多关于这个主题的资源,下面只是一个示例代码来帮助你理解这个想法:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor() { }
getTreeData(){
return this.http.get(`your api url goes here`);
}
}
最后一步是将服务注入到你的组件中,并订阅你在上一步中编写的函数,就像这样:
constructor(public api: ApiService ) { // don't forget to import the ApiService into your component
// subscribe to get the data
this.api.getTreeData().subscribe(
data => {
this.dataSource.data = data; // after reaching to this poin, angular will render your data automaticly instead of the example data.
}
);
}
很抱歉没有创建演示,但这对你来说应该没问题。
另外,如果您愿意,您可以稍后使用angular resolvers 来增强代码和性能。
如果有不清楚的地方请在下方评论。