0

I have this example JSON response from my backend that using Spring Boot. the "category" can be 1 or 2. 1 stand for Notification and 2 stands for FAQ

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

based on the json response this is the angular model that i created using ng g model command

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

This is the 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 : [];
}

This is the component.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);
}

}

and at the HTML im using swimlane ngx-datatable to show my all my data.

<!-- 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>

with my current code, my data displayed correctly. one thing that I don't know is how can I map/display my category value instead of displaying/rendering 1 or 2 in the browser, I would like to display them as their name (notification or FAQ)

1 Answers1

2

You can modify mapping your response to receive what you want, I'd do something like that:

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)
            });
        }),         
    );
}
Michał Tkaczyk
  • 732
  • 5
  • 18
  • Thank you for your help Actually I'm new to code especially javascript framework, typescript, and such but I'm eager to learn. Now I able to display what I wanted but I get one new problem which is the "...item" that shows a red curly underline on my VSCode. After I'm ng serve, the CLI shows this error : error TS2698: Spread types may only be created from object types. ...item, but on the browser, my app runs fine, every rows is shown and shows no error/warning at the console – Christopher Jordan Oct 23 '20 at 04:10
  • @ChristopherJordan I assume that type you defined is not correct. I'd like to know what you've defined in `GetResponse` and `NotifBase` types. – Michał Tkaczyk Oct 23 '20 at 06:27
  • actually i just defined GetResponse as an interface in the service.ts file like the code above and NotifBase as an angular model. (I've added the model that I created above). – Christopher Jordan Oct 23 '20 at 07:17
  • @ChristopherJordan I mean I'd like to see these files. Could you upload your app or at least this part of it on some code hosting service i.e. `stackblitz`? – Michał Tkaczyk Oct 23 '20 at 07:55
  • here is my [stackblizt](https://stackblitz.com/edit/angular-yftkre?file=src/app/app.component.ts) – Christopher Jordan Oct 26 '20 at 06:42
  • I see few typing mistakes. At first, you need to change all `String` to `string` in `getCategoryName` method, as they are not the same, you can read about that here: https://stackoverflow.com/questions/14727044/typescript-difference-between-string-and-string, second thing is you need to change type of `content` in `GetResponse` interface to `Array`. That should help :) – Michał Tkaczyk Oct 26 '20 at 12:21
  • Thank you it works perfectly. can I ask one thing, if I got a case were each object inside the content property has "notifBaseId" object and inside that object contain "notifId" and "category". how can I access them at getNotifList() method so I can map them? I've updated the [stackblitz](https://stackblitz.com/edit/angular-yftkre?devtoolsheight=33&file=src/app/services/notif.service.ts) if you don't mind to see it – Christopher Jordan Oct 28 '20 at 08:15
  • I don't know if I follow your question. You want to set these values inside every item in content array? If that's correct all you need to do is to set new property inside `content.map` function, just create new property in the same way as category, i.e. `notifBaseId: { notifId: item.notifId, category: item.category }`. Is that what you want to achieve? – Michał Tkaczyk Oct 28 '20 at 08:54