在Angular中使用Service
Service不仅仅是数据获取模块,同时也是非常简单容易的数据共享模块。
下面是是一个Service的定义:
board.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class BoardService {
constructor(private http: HttpClient) { }
backlog = [];
todo = [
'Task 1',
'Task 2',
'Task 3'
];
inProgess = [
'Task 4',
'Task 5',
];
done = [
'Task 6',
'Task 7',
'Task 8',
'Task 9'
];
boards = [
{id: 1, name: "Board 1"},
{id: 2, name: "Board 2"},
{id: 3, name: "Board 3"},
];
checkInvalidName(name: string): boolean {
if(this.todo.findIndex(x=>x.toLowerCase() == name.toLowerCase()) != -1){
return true;
}
if(this.inProgess.findIndex(x=>x.toLowerCase() == name.toLowerCase()) != -1){
return true;
}
if(this.done.findIndex(x=>x.toLowerCase() == name.toLowerCase()) != -1){
return true;
}
return false;
}
checkInvalidBoardName(name: string): boolean {
if(this.boards.findIndex(x=>x.name.toLowerCase() == name.toLowerCase()) != -1){
return true;
}
return false;
}
addBoard(name: string) {
return this.http.post<any>('/api/board', { name: name });
}
addTask(boardId: number, name: string) {
return this.http.post<any>('/api/task', { boardId: boardId, name: name });
}
getBoards() {
return this.http.get<any>('/api/board');
}
}
使用例子:
export class BoardComponent extends BaseComponent implements OnInit {
constructor(public dialog: MatDialog, private boardService: BoardService) {
super();
}
ngOnInit(): void {
this.backlog = this.boardService.backlog;
this.todo = this.boardService.todo;
this.inProgess = this.boardService.inProgess;
this.done = this.boardService.done;
this.subspritions.push(this.boardService.getBoards().subscribe(x=>{
this.boards = x;
if(this.boards.length > 0) {
this.currentBoardId = this.boards[0].id;
this.currentBoard = this.boards[0];
}
}));
} ...
可以在多个组件中使用:
export class AddBoardComponent {
constructor(@Inject(MAT_DIALOG_DATA) public data: any, public dialogRef: MatDialogRef<AddBoardComponent>,private boardService: BoardService) {
}
private isInvalidName = false;
closeDialogOk() {
// check unique
this.isInvalidName = this.boardService.checkInvalidBoardName(this.data.name);
if(this.isInvalidName) {
return;
}
this.dialogRef.close(this.data.name);
}
...
- 点赞
- 收藏
- 关注作者
评论(0)