前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用.net core ABP和Angular模板构建博客管理系统(实现博客列表页面)

使用.net core ABP和Angular模板构建博客管理系统(实现博客列表页面)

作者头像
易兒善
发布2018-08-21 15:27:23
8530
发布2018-08-21 15:27:23
举报
文章被收录于专栏:挖坑填坑挖坑填坑

创建服务

新建一个服务文件

代码语言:javascript
复制
ng g service blog/note-service

我们可以参考shared\service-proxies\service-proxies.ts文件来写我们的服务文件,这是模板提供的,看最上面的介绍,说的好像是用NSwag自动生成的,博主现在是用不了这个工具,有办法用的请指教。

image.png

service-proxies.ts

先把后台Api地址拷过来吧

代码语言:javascript
复制
// api域名
const ApiHost = 'http://localhost:21021';
// api地址
const NoteApiUrls = {
    Create: ApiHost + '/api/services/app/NoteAppServer/Create',
    PublicNote: ApiHost + '/api/services/app/NoteAppServer/PublicNote',
    Update: ApiHost + '/api/services/app/NoteAppServer/Update',
    GetAll: ApiHost + '/api/services/app/NoteAppServer/GetAll',
    GetNote: ApiHost +  '/api/services/app/NoteAppServer/GetNote',
    Delete:  ApiHost + '/api/services/app/NoteAppServer/Delete'
};

现在使用typeScript来写代码,创建服务基本和我们写后台的service差不多了。现在我们来定义数据的载体DTO,基本和后台一样。所以这个能用代码生成器生成也是很能理解的。

代码语言:javascript
复制
export class PageOfNoteDto {
    totalCount: number;
    items: NoteDto[];
}

export class CreateNoteDto {
    textType: number
}
// 首字母必须小写
export class NoteDto {
    title: string;
    creationTime: string;
    id: number;
    like: number;
    collect: number;
    scan: number;
    isPublic: boolean;
}

先照着写一个方法吧

代码语言:javascript
复制
import {SwaggerException} from '@shared/service-proxies/service-proxies';

export class NoteServiceService {
    protected jsonParseReviver: (key: string, value: any) => any = undefined;

    constructor(private http: Http) {

    }
    // 对于get请求我们要把参数拼接到url上面,这是api的特殊地方
    GetAll(MaxResultCount = 20, SkipCount = 0, key = ''): Observable<PageOfNoteDto> {
        let url_ = NoteApiUrls.GetAll + '?';
        url_ += 'SkipCount=' + encodeURIComponent('' + SkipCount) + '&';
        url_ += 'MaxResultCount=' + encodeURIComponent('' + MaxResultCount) + '&';
        url_ += 'key=' + encodeURIComponent('' + key);
        url_ = url_.replace(/[?&]$/, '');

        const options_ = {
            method: 'get',
            headers: new Headers({
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            })
        };
        return this.http.request(url_, options_).flatMap((response_) => {
            return this.processGetAll(response_);
        }).catch((response_: any) => {
            if (response_ instanceof Response) {
                try {
                    return this.processGetAll(response_);
                } catch (e) {
                    return <Observable<PageOfNoteDto>><any>Observable.throw(e);
                }
            } else
                return <Observable<PageOfNoteDto>><any>Observable.throw(response_);
        });
    }

    protected processGetAll(response: Response): Observable<PageOfNoteDto> {
        const status = response.status;

        const _headers: any = response.headers ? response.headers.toJSON() : {};
        if (status === 200) {
            const _responseText = response.text();
            let result200: any = null;
            const resultData200 = _responseText === '' ? null : JSON.parse(_responseText, this.jsonParseReviver);
            result200 = resultData200 ? resultData200 as PageOfNoteDto : new PageOfNoteDto();
            console.log(_responseText);
            console.log(result200);
            console.log(resultData200);
            return Observable.of(result200);
        } else if (status === 401) {
            const _responseText = response.text();
            return this.throwException('服务器错误', status, _responseText, _headers);
        } else if (status === 403) {
            const _responseText = response.text();
            return this.throwException('服务器错误', status, _responseText, _headers);
        } else if (status !== 200 && status !== 204) {
            const _responseText = response.text();
            return this.throwException('意料之外的出现', status, _responseText, _headers);
        }
        return Observable.of<PageOfNoteDto>(<any>null);
    }

    protected throwException(message: string, status: number, response: string,
                             headers: { [key: string]: any; }, result?: any): Observable<any> {
        if (result !== null && result !== undefined) {
            return Observable.throw(result);
        } else {
            return Observable.throw(new SwaggerException(message, status, response, headers, null));
        }
    }
}

使用服务

在我们的note.component.ts中引入来看看我们服务对不对。

代码语言:javascript
复制
import { Component, OnInit, Injector } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { PagedListingComponentBase, PagedRequestDto } from 'shared/paged-listing-component-base';
import {NoteDto, NoteServiceService, PageOfNoteDto} from '@app/blog/note-service.service'

@Component({
  selector: 'app-note',
  templateUrl: './note.component.html',
  styleUrls: ['./note.component.css'],
    animations: [appModuleAnimation()]
})
export class NoteComponent extends PagedListingComponentBase<NoteDto> {

  constructor(private noteService: NoteServiceService,
              injector: Injector) {
      super(injector);
  }

    protected list(request: PagedRequestDto, pageNumber: number, finishedCallback: Function): void {
        this.noteService.GetAll(20, 0 )
            .finally(() => {
                finishedCallback();
            })
            .subscribe((result: PageOfNoteDto) => {
                console.log(result);
            });
    }

    protected delete(user: NoteDto): void {

    }

}

出错了,服务没有提供

是因为在app.module.ts里面没有引入的原因:

代码语言:javascript
复制
import {NoteServiceService} from '@app/blog/note-service.service'
    providers: [
        NoteServiceService
    ]

再试一下呢。

没有权限啊~~~

在角色管理页面给当前用户的角色添加notes这个权限。因为我们后台添加了访问权限的

给当前用户添加权限

控制台没有报错,还打印出来一些东西,貌似就是我们后台传来的数据

看来通信正常,可以继续完善页面了。

代码语言:javascript
复制
 notes: NoteDto[]; // 文章列表
    protected list(request: PagedRequestDto, pageNumber: number, finishedCallback: Function): void {
        this.noteService.GetAll(request.maxResultCount, request.skipCount)
            .finally(() => {
                finishedCallback();
            })
            .subscribe((result: PageOfNoteDto) => {
                this.notes = result.items;
                this.showPaging(result, pageNumber);
            });
    }

把用户页面(users.component.html)的内容拷贝过来,放在我们note.component.html文件里,进行如下修改。

代码语言:javascript
复制
<div class="row clearfix" [@routerTransition]>
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
        <div class="card main-content">
            <div class="header">
                <h2>
                    文章列表
                </h2>
                <ul class="header-dropdown m-r--5">
                    <i class="fa fa-spin fa-spinner" *ngIf="isTableLoading"></i>
                    <li class="dropdown">
                        <a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
                            <i class="material-icons">more_vert</i>
                        </a>
                        <ul class="dropdown-menu pull-right">
                            <li><a href="javascript:void(0);" class=" waves-effect waves-block()" (click)="refresh();"><i class="material-icons">refresh</i> {{l('Refresh')}}</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
            <div class="body table-responsive">

                <!-- ******************************************************** -->
                <table class="table table-hover table-striped">
                    <thead>
                    <tr>
                        <th>文章标题</th>
                        <th>阅读次数</th>
                        <th>点赞次数</th>
                        <th>
                            <div style="text-align:center">是否发布</div>
                        </th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr *ngFor="let note of notes | paginate: { id: 'server', itemsPerPage: pageSize, currentPage: pageNumber, totalItems: totalItems }">
                        <td>{{note.title}}</td>
                        <td>{{note.scan}}</td>
                        <td>{{note.like}}</td>
                        <td align="center">
                            <i class="material-icons" *ngIf="note.isPublic" style="color:green;">check_box</i>
                            <i class="material-icons" *ngIf="!note.isPublic" style="color:red;">indeterminate_check_box</i>
                        </td>
                        <td>{{note.creationTime}}</td>
                        <td class="dropdown">
                            <a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
                                <i class="material-icons">menu</i>
                            </a>
                            <ul class="dropdown-menu pull-right">
                                <li><a href="javascript:void(0);" class="waves-effect waves-block" (click)="editUser(note)"><i class="material-icons">create</i>编辑}</a></li>
                                <li><a href="javascript:void(0);" class="waves-effect waves-block" (click)="delete(note)"><i class="material-icons">delete_sweep</i>修改</a></li>
                            </ul>
                        </td>
                    </tr>
                    </tbody>
                </table>
                <!-- ******************************************************** -->

                <div class="text-align: center;" *ngIf="totalItems > pageSize">
                    <pagination-controls (pageChange)="getDataPage($event)" id="server"></pagination-controls>
                </div>
                <button type="button" data-toggle="modal" class="btn btn-primary btn-circle waves-effect waves-circle waves-float pull-right" (click)="createUser()">
                    <i class="material-icons">add</i>
                </button>
            </div>
        </div>
    </div>
</div>

数据库里只有两条测试数据

思考

  • 我们继承了PagedListingComponentBase类,可以仔细看看这个类的定义,学习下高级架构师在封装这些公用基类时都考虑了些什么,我们该如何来扩展。
  • {l('Users')}是什么意思,l是本地化的意思,可以根据我们界面右上角的语言选择来自动显示不同的语言文字。后面将要学习下如何使用,这显得我们的软件更加的国际化。
  • 既然我们用不了代码生成器,那么完全照着抄写service是不是很累? 我们可以自自己写一个dto的代码生成器,至于service我们可以抽象出一个基类来嘛。
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.11.05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 创建服务
  • 使用服务
  • 思考
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档