【问题标题】:Failure while implementing a tree view from an API in Angular 9从 Angular 9 中的 API 实现树视图时失败
【发布时间】:2020-03-13 11:55:30
【问题描述】:

我正在尝试实现一个 Material Design Tree View,它完全从 API 加载数据。但是,我的实现抛出了错误。 HttpClient 导入似乎很好,我不明白有什么问题。我尝试修改代码但无济于事。

我的 .scss 文件:

.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;
}

我的 .html 文件:

<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>

我的 .ts 文件:

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;
}



我的错误:

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!

我做错了什么?


更新

我的 JSON,从 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"
         }
      ]
   }
]

【问题讨论】:

    标签: angular typescript tree treeview material-design


    【解决方案1】:

    您的模块中缺少 HttpClientModule 导入。

    将以下内容添加到 app.module.ts:

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

    然后在导入部分添加

     imports:[HttpClientModule,  ]
    

    查看 Angular 9 Stackblitz

    编辑:

    有关工作 mat-tree 示例,请查看 Angular Mat-Tree docs

    编辑2:

    为您的示例工作Stackblitz,但您必须设置自己的网址;-)

    【讨论】:

    • 现在我收到了core.js:5882 ERROR TypeError: Cannot read property 'push' of undefined
    • this.TREE_DATA 似乎是 undefined ;-) TREE_DATA 不是班级成员,实际上你不能使用 this
    • 但我是用const TREE_DATA: FoodNode[] = []; 定义的,不是吗?
    • 好的,我删除了这个,现在没有错误了,console.log输出正确的数据,但是没有显示树。
    • 如果不推送任何数据,则树为空=)
    猜你喜欢
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    相关资源
    最近更新 更多