首页 > 解决方案 > 使用 Angular 10 将 JSON 值映射到新字符串以在 HTML 中显示

问题描述

我的后端有这个使用 Spring Boot 的示例 JSON 响应。“类别”可以是 1 或 2。1 代表通知,2 代表常见问题

{
"pageNumber": 0,
"size": 5,
"totalPages": 39,
"content": [
    {
        "notifBaseId": {
            "notifId": "11115"
        },
        "notifLngCd": "en",
        "title": "Test",
        "ctt": lorem ipsum",
        "category": "2",
    },

基于 json 响应,这是我使用 ng g model 命令创建的角度模型

export class NotifBase {
notifID : string;
notifLngCd : string;
title : string;
ctt : string;
category : string;
}

这是service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { NotifBase } from '../model/notif-base';

@Injectable({
  providedIn: 'root'
})
export class NotifBaseService {
    
    private URL  = 'http://localhost:1001/api/notif/base';

    constructor ( private httpClient : HttpClient ) { }
    /** 
     * this is for default way for ngx-datatable 
     * 
     * */
    getNotifBaseList() : Observable<NotifBase[]> {
        return this.httpClient.get<GetResponse>(this.URL).pipe(
            map(response => response.content),
            
        );
    }

}

/*
This is for mapping the JSON endpoint
*/
interface GetResponse {
    content : [];
}

这是组件.ts

export class NotifBaseComponent implements OnInit {

//Table Rows
notifRows: NotifBase[];
// table Column 
notifColumns = [
    { name : 'NotifId', prop : 'notifBaseId.notifId'},
    { name : 'Languange', prop : 'notifLngCd'},
    { name : 'Notif title', prop : 'title'},
    { name : 'Content', prop : 'ctt'},
    { name : 'Category', prop : 'category},
];
selected = [];
SelectionType = SelectionType;
ColumnMode = ColumnMode;

constructor( private notifBaseService: NotifBaseService ){
    
}

ngOnInit(){
    this.loadAll();
}

loadAll(){
    this.notifBaseService.getNotifBaseList().subscribe(
        data => {
            this.notifRows = data;
        }
    );
}

/**
 * This is for selected rows event
 */
onSelect({ selected }) {
    console.log('Select Event', selected, this.selected);
}
onActivate(event) {
    console.log('Activate Event', event);
}

}

并在 HTML 即时通讯中使用泳道 ngx-datatable 显示我的所有数据。

<!-- Ngx datatable  -->
    <ngx-datatable 
        class="material"
        [rows]="notifRows"
        [columnMode]="'standard'"
        [columns]="notifColumns"
        [headerHeight] ="50"
        [footerHeight]="50"
        [rowHeight]="50"
        [scrollbarH]="true"
        [scrollbarV]="true"
        [selected]="selected"
        [selectionType]="SelectionType.single"
        
    >
    </ngx-datatable>

使用我当前的代码,我的数据正确显示。我不知道的一件事是如何映射/显示我的类别值而不是在浏览器中显示/呈现 1 或 2,我想将它们显示为他们的名称(通知或常见问题解答)

标签: javascripthtmlangulartypescriptngx-datatable

解决方案


您可以修改映射您的响应以接收您想要的内容,我会这样做:

getCategoryName(id: string): string {
    if (id === '1') {
        return 'Notification';
    }

    if (id === '2') {
        return 'FAQ';
    }

    return 'Unknown';
}

getNotifBaseList() : Observable<NotifBase[]> {
    return this.httpClient.get<GetResponse>(this.URL).pipe(
        map(response => {
            return response.content.map(item => ({
                ...item,
                category: this.getCategoryName(item.category)
            });
        }),         
    );
}

推荐阅读