Initialize Array in constructor and pass into map in Angular

1.3k views Asked by At

I am trying to create a model in angular and passing that into map function in service. I have one array in that model. When I pass that its showing undefined and except that array rest of the values are coming well. I think I am doing wrong in initializing and calling array. Can any tell me how to do it.

abc.ts

export class ABC {
    date: Date;
    time: string;
    abc_Info: {
        item: string,
        quantity: number,
        a: number
    } []
    constructor(date: Date, time: string, abc_Info: []) {
        this.date = date;
        this.time = time;
        this.abc_Info = abc_Info;
    }
}

abc.service

import { ABC} from './models/abc';
getABC(start ? : moment.Moment, end ? : moment.Moment): Observable < ABC[] > {
    let params = new HttpParams();
    if (start) {
        params = params.append('start', start.toISOString());
    }
    if (end) {
        params = params.append('end', end.toISOString());
    }
    return this.baseService.getParams('/api/abc/getAll', params)
        .pipe(
            map(res => res as Object[] || []),
            map(bolus => bolus.map(k => new Bolus(
                    new Date(k['date']), //Value passing and coming well
                    k['time'], //Value passing and coming well
                    k['abc_Info'] //calling array here, showing undefined when i run
      ))))
}

Response In Back end, This is what I am getting into front end

[
  {
    "date": "2019-01-18T18:30:00.000Z",
    "time": "2019-01-19T04:52:00.389Z",
    "abc_Info": [
      {
        "_id": "5c42acf9a0048b2a683be22a",
        "item": "Idly",
        "quantity": 15,
        "a": 30
      },
      {
        "_id": "5c42acf9a0048b2a683be229",
        "item": "Sandwitch",
        "quantity": 10,
        "a": 25
      },
      {
        "_id": "5c42acf9a0048b2a683be228",
        "item": "Sandwitch",
        "quantity": 20,
        "a": 25
      }
    ]
  }
]
1

There are 1 answers

0
Hearen On

There several places you are using the get() weirdly, actually you should try to use more of the TypeScript.

If the response is already json then you can use

this.http.get<ABC[]>(req);   

If the response is text format then perhaps you can directly use

this.http.get<string>(req).pipe(map(s => JSON.parse(s)));
// get the typed array directly

Via this basic trick we can directly get the data and present it with

<div *ngFor="let c of _ret">
  <h3>{{ c.time }}</h3>
  <ul>
     <li *ngFor="let info of c.abc_Info">{{ info["item"] }} : {{ info["quantity"] }}</li>
  </ul>
</div>

You can check the online demo in which I am using interceptor to mock the server response.