iT邦幫忙

2022 iThome 鐵人賽

DAY 14
0
Modern Web

angular專案開發指南系列 第 14

實作租戶管理頁面(2)

  • 分享至 

  • xImage
  •  

前言

利用 JSON Server 快速模擬 Restful API,支援開發中最常用的 GET、POST、PUT、PATCH、DELETE、OPTIONS 等方法,
接下來我們就用 POST 模擬新增資料PUT 模擬修改資料DELETE 模擬刪除資料,把租戶管理頁面的完整功能做完吧。


新增租戶

[POST] API - 新增租戶 src\app\core\services\http.service.ts

async httpPOST(...args: any[]): Promise<object> {
    const apiUrl = args[0] || '';
    const body = args[1] || {};

    try {
        const result$ = this.httpClient.post(apiUrl, body).pipe(
            tap((resp: IHttpResponse) => {
                return resp;
            })
        );

        return await lastValueFrom(result$);
    } catch (err) {
        return Promise.reject(err);
    }
}

新增租戶對話框 src\app\tenant\tenant.component.html

為方便使用者新增租戶資料,添加對話框如下,

<!-- Dialog Template -->
<ng-template #dialog let-data let-ref="dialogRef">
    <nb-card class="tenant-dialog">
        <nb-card-header>新增租戶</nb-card-header>
        <nb-card-body>
            <div>
                <label>First Name   </label>
                <input type="text" nbInput [(ngModel)]="addTenant.fname" />
            </div>
            <div>
                <label>Last Name   </label>
                <input type="text" nbInput [(ngModel)]="addTenant.lname" />
            </div>
            <div>
                <label>Phone Number   </label>
                <input type="number" nbInput [(ngModel)]="addTenant.phone" />
            </div>
            <div>
                <label>Address   </label>
                <input type="text" nbInput [(ngModel)]="addTenant.address" />
            </div>
        </nb-card-body>
        <nb-card-footer>
            <button nbButton status="primary" (click)="ref.close('ok')">確定</button>
             
            <button nbButton (click)="ref.close()">取消</button>
        </nb-card-footer>
    </nb-card>
</ng-template>

美化樣式 src\app\tenant\tenant.component.scss

.tenant-dialog {
    nb-card-body {
        div {
            display: flex;
            justify-content: space-between;
            margin: 1rem 0;
        }
    }
}

注入 NbDialogService 服務 src\app\tenant\tenant.component.ts

import { NbDialogService } from '@nebular/theme';

export class TenantComponent implements OnInit {
    constructor(private httpService: HttpService, private nbDialogService: NbDialogService) {}

    addTenant = {
        fname: '',
        lname: '',
        phone: '',
        address: '',
    };

    async addItem(dialog: TemplateRef<any>) {
        this.nbDialogService
            .open(dialog, {
                context: {
                    content: `<div>Hello</div>`,
                },
            })
            .onClose.subscribe(async (dialogResp) => {
                if (dialogResp === 'ok') {
                    const result: any = {
                        first_name: this.addTenant.fname,
                        last_name: this.addTenant.lname,
                        phone: this.addTenant.phone,
                        address: this.addTenant.address,
                    };

                    // 調用新增租戶 API
                    await this.httpService.httpPOST(this.host + '/myapp-tenant-list', result);
                    this.queryTenantList.push(result);

                    // 清空對話框資料
                    this.addTenant.fname = '';
                    this.addTenant.lname = '';
                    this.addTenant.phone = '';
                    this.addTenant.address = '';
                }
            });
    }
}

p60

畫面刷新可見新增租戶結果

p61


修改租戶

[PUT] API - 修改租戶 src\app\core\services\http.service.ts

async httpPUT(...args: any[]): Promise<object> {
    const apiUrl = args[0] || '';
    const body = args[1] || {};

    try {
        const result$ = this.httpClient.put(apiUrl, body).pipe(
            tap((resp: IHttpResponse) => {
                return resp;
            })
        );

        return await lastValueFrom(result$);
    } catch (err) {
        return Promise.reject(err);
    }
}

修改租戶對話框 src\app\tenant\tenant.component.html

使用跟新增租戶時同樣的對話框,把被選擇的資料寫入 在 ngFor 後面需要加入 let i = index

<nb-list-item *ngFor="let tenant of queryTenantList; let i = index" (click)="editItem(dialog, i)">
    <nb-user size="large" [title]="tenant['phone']" name="{{ tenant['first_name'] }} {{ tenant['last_name'] }}">
    </nb-user>
</nb-list-item>

增加 editItem 方法 src\app\tenant\tenant.component.ts

editItem(dialog: TemplateRef<any>, idx: number) {
    const url = this.host + '/myapp-tenant-list/' + (idx + 1);
    const targetObj = this.queryTenantList[idx];

    // 被選擇項目資料寫入對話框
    this.addTenant.fname = targetObj.first_name;
    this.addTenant.lname = targetObj.last_name;
    this.addTenant.phone = targetObj.phone;
    this.addTenant.address = targetObj.address;

    this.nbDialogService.open(dialog).onClose.subscribe(async (dialogResp) => {
        if (dialogResp === 'ok') {
            const result: any = {
                id: idx,
                first_name: this.addTenant.fname,
                last_name: this.addTenant.lname,
                phone: this.addTenant.phone,
                address: this.addTenant.address,
            };

            // 調用修改租戶 API
            await this.httpService.httpPUT(url, result);
            this.queryTenantList[idx] = result;
        }
    });
}

g2


刪除租戶

[DELETE] API - 修改租戶 src\app\core\services\http.service.ts

async httpDelete(...args: any[]): Promise<object> {
    const apiUrl = args[0] || '';

    try {
        const result$ = this.httpClient.delete(apiUrl);

        return await lastValueFrom(result$);
    } catch (err) {
        return Promise.reject(err);
    }
}

刪除租戶對話框 src\app\tenant\tenant.component.html

直接把刪除按鈕放在剛才的對話框,樣式需要做一些調整。

<nb-card-footer>
    <div>
        <button nbButton status="primary" (click)="ref.close('ok')">確定</button>
         
        <button nbButton (click)="ref.close()">取消</button>
    </div>
    <div>
        <button nbButton status="danger" *ngIf="data.type === 'edit'" (click)="ref.close('delete')">
            刪除
        </button>
    </div>
</nb-card-footer>

美化樣式 src\app\tenant\tenant.component.scss

.tenant-dialog {
    nb-card-body {
        div {
            display: flex;
            justify-content: space-between;
            margin: 1rem 0;
        }
    }

    nb-card-footer {
        display: flex;
        justify-content: space-between;
    }
}

editItem 添加調用刪除租戶 src\app\tenant\tenant.component.ts

this.nbDialogService
.open(dialog, {
    context: {
        type: 'edit',
        title: '編輯租戶',
    },
})
.onClose.subscribe(async (dialogResp) => {
    if (dialogResp === 'ok') {
        const result: any = {
            id: idx,
            first_name: this.addTenant.fname,
            last_name: this.addTenant.lname,
            phone: this.addTenant.phone,
            address: this.addTenant.address,
        };

        // 調用修改租戶 API
        await this.httpService.httpPUT(url, result);
        this.queryTenantList[idx] = result;
    } else if (dialogResp === 'delete') {
        // 調用刪除租戶 API
        await this.httpService.httpDelete(url);
        this.queryTenantList.splice(idx, 1);
    }
});

g3


結論

在本篇我們練習了如何利用 JSON Server 模擬 POST 新增資料PUT 修改資料DELETE 刪除資料,並使用了 NbDialogService 的對話框服務進行租戶管理,完整的練習了租戶管理頁面的 CRUD 功能。

在填寫租戶資訊的時候都沒有做一些基本的檢查,接下來我們會介紹一下 Angular 的表單驗證,讓資料更符合存入資料庫的需求。


參考

JSON Server

Create A REST API With JSON Server


上一篇
實作租戶管理頁面(1)
下一篇
Angular 表單驗證
系列文
angular專案開發指南30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言