创建服务
新建一个服务文件
ng g service blog/note-service
image.png service-proxies.ts我们可以参考shared\service-proxies\service-proxies.ts文件来写我们的服务文件,这是模板提供的,看最上面的介绍,说的好像是用NSwag自动生成的,博主现在是用不了这个工具,有办法用的请指教。
先把后台Api地址拷过来吧
// 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,基本和后台一样。所以这个能用代码生成器生成也是很能理解的。
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;
}
先照着写一个方法吧
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中引入来看看我们服务对不对。
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里面没有引入的原因:
import {NoteServiceService} from '@app/blog/note-service.service'
providers: [
NoteServiceService
]
没有权限啊~~~再试一下呢。
给当前用户添加权限 控制台没有报错,还打印出来一些东西,貌似就是我们后台传来的数据在角色管理页面给当前用户的角色添加notes这个权限。因为我们后台添加了访问权限的
看来通信正常,可以继续完善页面了。
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文件里,进行如下修改。
<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我们可以抽象出一个基类来嘛。
网友评论