Angular 利用HttpClient取回後端資料

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import {HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
selector: 'app-test-list',
imports: [NgFor],
templateUrl: './test-list.component.html',
styleUrl: './test-list.component.scss'
})

export class TestListComponent implements OnInit {
getLists() {
const apiUrl ="https://xxxx"
this.http.get<addListsType[]>(`${apiUrl}/api/toDoLists`, this.httpOptions).pipe(catchError(this.handleError))
.subscribe((lists )=> {
consle.log(lists)
this.todoDataList = lists;
})
}
}

上範例Ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import {HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
selector: 'app-test-list',
imports: [NgFor],
templateUrl: './test-list.component.html',
styleUrl: './test-list.component.scss'
})

export class TestListComponent implements OnInit {
constructor( private http: HttpClient ) { }
private readonly httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
private handleError(error: any) {
console.error('API 錯誤:', error);
return throwError(() => new Error(error.message || '錯誤已消失'));
}
todoDataList: addListsType[] = [];
tableHeader: string[] = ['項目','名稱','建立日期','更新日期','操作'];
getLists() {
const apiUrl ="https://xxxx"
this.http.get<addListsType[]>(`${apiUrl}/api/toDoLists`, this.httpOptions).pipe(catchError(this.handleError))
.subscribe((lists )=> {
let arrLists:any[] = [];
lists.map( (item: any,index:number) => {
let query: any = {
_id: item._id,
title: item.title,
Editing: false, // 編輯
Status: false, //選取狀態
CanEdit: true, //可以編輯
buildDate: item.buildDate,
updataDate: item.buildDate,
}
// 新增的欄位push 到陣列
arrLists.push(query);

//排序
arrLists.sort((a, b) => {
return b.buildDate - a.buildDate
})
})
//渲染的陣列等於新增後後的陣列
this.todoDataList = arrLists;
})
}
}

html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<table class="table table-striped">
<thead >
<tr >
<th *ngFor="let item of tableHeader| slice: 0 : 5 ;let index = index " scope="col">{{item}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of todoDataList;let index = index">
<td>{{index +1}}</td>
<td>{{item.title | uppercase }} </td>
<td>{{item.buildDate | date:'yyyy-MM-dd HH:mm' }} </td>
<td>{{item.updataDate | TaiwanYear }} </td>

<td>
<button type="button" class="btn btn-secondary">Cancel</button>
<button type="button" class="btn btn-success ml-2">Submit</button></td>
</tr>
</tbody>
</table>


參考