在Angular中使用Service
Service不僅僅是數(shù)據(jù)獲取模塊,同時(shí)也是非常簡單容易的數(shù)據(jù)共享模塊。
下面是是一個(gè)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
}
addTask(boardId:?number,?name:?string)?{
return??this.http.post
}
getBoards()?{
return??this.http.get
}
}
使用例子:
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];
}
}));
}?...
可以在多個(gè)組件中使用:
export?class?AddBoardComponent?{
constructor(@Inject(MAT_DIALOG_DATA)?public?data:?any,?public?dialogRef:?MatDialogRef
}
private?isInvalidName?=?false;
closeDialogOk()?{
//?check?unique
this.isInvalidName?=?this.boardService.checkInvalidBoardName(this.data.name);
if(this.isInvalidName)?{
return;
}
this.dialogRef.close(this.data.name);
}
...
Angular
版權(quán)聲明:本文內(nèi)容由網(wǎng)絡(luò)用戶投稿,版權(quán)歸原作者所有,本站不擁有其著作權(quán),亦不承擔(dān)相應(yīng)法律責(zé)任。如果您發(fā)現(xiàn)本站中有涉嫌抄襲或描述失實(shí)的內(nèi)容,請聯(lián)系我們jiasou666@gmail.com 處理,核實(shí)后本網(wǎng)站將在24小時(shí)內(nèi)刪除侵權(quán)內(nèi)容。