发表于: 2019-10-23 22:24:02

1 838


Angular后台管理系统获取后台接口数据的方法

如下图,angular后台管理系统框架已搭建完成,接下来就是请求后台接口的数据,并渲染到页面上


1.使用antd官网 https://ng.ant.design/components/table/zh的table表格组件,首先引入表格模块

import { NzTableModule } from 'ng-zorro-antd/table';
article的html中引用table其中一个模板
<nz-table #basicTable [nzData]="listOfData">
    <thead>
      <tr>
        <th>Name</th>
        <th>Age</th>
        <th>Address</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let data of basicTable.data">
        <td>{{ data.name }}</td>
        <td>{{ data.age }}</td>
        <td>{{ data.address }}</td>
        <td>
          <a>Action 一 {{ data.name }}</a>
          <nz-divider nzType="vertical"></nz-divider>
          <a>Delete</a>
        </td>
      </tr>
    </tbody>
  </nz-table>
这里也可以将模板中的假数据复制到tarticle的ts文件中看一下效果,没问题后假数据就删除掉


2.在article的ts文件中引入之前新建的service文件并且初始化

import { ServiceService} from '../../login/service.service'
constructor(public ser:ServiceService) { }
在service文件中定义获取数据的接口地址
public geturl:string = '/a/article/search';
在service文件中定义一个获取数据的方法,这个方法最终是被article中调用,所以这里用return返回
  getData(){
    return this.http.get(
      this.posturl
    )
  }


3.在article的ts文件中定义一个方法,方法是不会自己执行的,所以在声明周期函数内调用,这里面的代码或者函数在页面加载的时候自动执行

  ngOnInit() {
    this.getTable();
  }
    定义的方法如下
  getTable(){
    this.ser.getData().subscribe((res:any)=>{
      console.log(res)//这里的res是从后台接受的返回参数
    })
  }
这里打印出来可以看到后台给我们返回了很多数据,如下图
但是我们需要的是articleList这个数组的数据,这里我们在定义一个空数组
public bbb:[];
然后再getTable方法中将得到的数组传递给这个空数组
  getTable(){
    this.ser.getData().subscribe((res:any)=>{
      console.log(res)//这里的res是从后台接受的返回参数
      this.bbb = res.data.articleList;
    })
  }
最后再html文件中修改源文件将数组中的数据使用for循环取出来
<nz-table #basicTable [nzData]="bbb">
    <thead>
      <tr>
        <th>ID</th>
        <th>名称</th>
        <th>类型</th>
        <th>发布时间</th>
        <th>修改时间</th>
        <th>发布者</th>
        <th>状态</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let data of bbb">
        <td>{{ data.id }}</td>
        <td>{{ data.title }}</td>
        <td>{{ data.type }}</td>
        <td>{{ data.createAt }}</td>
        <td>{{ data.updateAt }}</td>
        <td>{{ data.status }}</td>
        <td>
          <a>Action 一 {{ data.name }}</a>
          <nz-divider nzType="vertical"></nz-divider>
          <a>Delete</a>
        </td>
      </tr>
    </tbody>
  </nz-table>
4.页面如下表代表数据获取成功,由于目前分页功能未实现,所以只能展示部分数据




返回列表 返回列表
评论

    分享到