TransWikia.com

Failure while implementing a tree view from an API in Angular 9

Stack Overflow Asked by Munchkin on December 25, 2021

I am trying to implement a Material Design Tree View, which completely loads the data from an API. However, my implementation is throwing out errors. The HttpClient import seems to be fine, I don’t get what is wrong. I tried mendling with the code without any avail.

My .scss file:

.example-tree-progress-bar {
  margin-left: 30px;
}

.example-tree-invisible {
  display: none;
}

.example-tree ul,
.example-tree li {
  margin-top: 0;
  margin-bottom: 0;
  list-style-type: none;
}

My .html file:

<mat-tree [dataSource]="dataSource" [treeControl]="treeControl" class="example-tree">
  <!-- This is the tree node template for leaf nodes -->
  <mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggle>
    <li class="mat-tree-node">
      <!-- use a disabled button to provide padding for tree leaf -->
      <button mat-icon-button disabled></button>
      {{node.name}}
    </li>
  </mat-tree-node>
  <!-- This is the tree node template for expandable nodes -->
  <mat-nested-tree-node *matTreeNodeDef="let node; when: hasChild">
    <li>
      <div class="mat-tree-node">
        <button mat-icon-button matTreeNodeToggle
                [attr.aria-label]="'toggle ' + node.name">
          <mat-icon class="mat-icon-rtl-mirror">
            {{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
          </mat-icon>
        </button>
        {{node.name}}
      </div>
      <ul [class.example-tree-invisible]="!treeControl.isExpanded(node)">
        <ng-container matTreeNodeOutlet></ng-container>
      </ul>
    </li>
  </mat-nested-tree-node>
</mat-tree>

My .ts file:

import {NestedTreeControl} from '@angular/cdk/tree';
import {Component} from '@angular/core';
import {MatTreeNestedDataSource} from '@angular/material/tree';
import { HttpClient, HttpHeaders } from '@angular/common/http';

/**
 * Food data with nested structure.
 * Each node has a name and an optional list of children.
 */
interface FoodNode {
  name: string;
  children?: FoodNode[];
}

/* const TREE_DATA: FoodNode[] = [
  {
    name: 'Fruit',
    children: [
      {name: 'Apple'},
      {name: 'Banana'},
      {name: 'Fruit loops'},
    ]
  }, {
    name: 'Vegetables',
    children: [
      {
        name: 'Green',
        children: [
          {name: 'Broccoli'},
          {name: 'Brussels sprouts'},
        ]
      }, {
        name: 'Orange',
        children: [
          {name: 'Pumpkins'},
          {name: 'Carrots'},
        ]
      },
    ]
  },
]; */



const TREE_DATA: FoodNode[] = [];



/**
 * @title Tree with nested nodes
 */
@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss'],
})
export class TreeNestedOverviewExample {
  treeControl = new NestedTreeControl<FoodNode>(node => node.children);
  dataSource = new MatTreeNestedDataSource<FoodNode>();

  constructor(private client: HttpClient) {
    this.dataSource.data = TREE_DATA;

  }

  ngOnInit() {
    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json' })
    };
    const API_URL = 'https://urlhere.com/gettreeview';
  this.client.get(API_URL, this.httpOptions).subscribe(
    (res) => { this.TREE_DATA.push(res);console.log('Res: ', res); },
  );
  }

  hasChild = (_: number, node: FoodNode) => !!node.children && node.children.length > 0;
}



My errors:

core.js:5882 ERROR NullInjectorError: R3InjectorError(AppModule)[HttpClient -> HttpClient -> HttpClient]: 
  NullInjectorError: No provider for HttpClient!
main.ts:12 NullInjectorError: R3InjectorError(AppModule)[HttpClient -> HttpClient -> HttpClient]: 
  NullInjectorError: No provider for HttpClient!

What am I doing wrong?


UPDATE

My JSON, which is fetched from the API:

[
   {
      "id": 1,
      "name": "- Admin",
      "children": [
         {
            "id": 2,
            "name": "Jimmy"
         },
         {
            "id": 3,
            "name": "Tom"
         }
      ]
   },
   {
      "id": 4,
      "name": "- Users",
      "children": [
         {
            "id": 5,
            "name": "Scott"
         },
         {
            "id": 6,
            "name": "John"
         }
      ]
   },
   {
      "id": 7,
      "name": "- Developer",
      "children": [
         {
            "id": 8,
            "name": "Robert"
         },
         {
            "id": 9,
            "name": "Scarlett"
         },
         {
            "id": 10,
            "name": "Johnson"
         }
      ]
   }
]

One Answer

Your are missing the HttpClientModule import in your module.

Add the following to app.module.ts:

import { HttpClientModule } from '@angular/common/http'; 

After that add in the import section like

 imports:[HttpClientModule,  ]

See working Angular 9 Stackblitz

Edit:

For working mat-tree examples check Angular Mat-Tree docs

Edit2:

Working Stackblitz for your example, but you have to set your own url ;-)

Answered by zerocewl on December 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP