I am new to the Angular framework and want to generate a mat-tree from REST API which is made in MongoDB. I have created a model in the backend for retrieving data from the backend database. Below is a code which is written on the backend server configuration.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let MainTree = new Schema({
id: {
type: String
},
name: {
type: String
},
children: {
type: Array
}
}, {
collection: 'TreeData'
})
module.exports = mongoose.model('MainTree', MainTree)
tree.routee.js this file defining route and functions which can be called by service api.
const express = require('express');
const app = express();
const treeRoute = express.Router();
let TreeData = require('../models/MainTree');
treeRoute.route('/').get((req, res) => {
TreeData.find((error, data) => {
if (error) {
return next(error)
} else {
res.json(data)
}
})
})
module.exports = treeRoute;
tree.service.ts this is service api
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class TreeService {
baseUri:string = 'http://localhost:4000/api';
constructor(private http: HttpClient) { }
getTreeData(){
return this.http.get(`${this.baseUri}`);
}
}
demo-tree.component.ts this is component.ts file which is getting data from backend via tree.service.ts
import { Component, OnInit } from '@angular/core';
import { TreeService } from '../service/tree.service';
@Component({
selector: 'app-demo-tree',
templateUrl: './demo-tree.component.html',
styleUrls: ['./demo-tree.component.css']
})
export class DemoTreeComponent implements OnInit {
Tree:any = [];
constructor(private Data: TreeService) { }
getData(){
this.Data.getTreeData().subscribe((data) => {
this.Tree = data;
})
}
ngOnInit() {
}
}
demo-tree.component.html this is HTML file which is retrieving Tree Array, showing message 'There is no item added yet!' and this is right because we have not added any item or node in backend database.
<p *ngIf="Tree.length <= 0" class="no-data text-center">There is no item added yet!</p>
else showing mat-tree data like that.
I want to know how I can make a tree-like structure in my backend server and retrieve that data. Is there a way to generate a mat-tree from a Database? I have read the answer to this question but didn't appropriate for my requirement.
Thanks.