Glen
Glen

Reputation: 331

Map in Angular 10 array of list objects

This is WORKING service class for which return single transaction

getEditTransactionById(id: number): Observable<ITransaction> {
    return this.httpClient.get<Result<ITransaction>>(baseUrl'/Transaction/GetEditTransactionById'+ `/${id}`)       
    .pipe(
        map((res)=>{
            res.data.valueDate = new Date(res.data.valueDate);       
            return res.data;
        })
    )
}

Actually how I need to change the date format of fields valuedate in array coming from API

Could you please help?

This is my service class which returns array ...Need to change the date format

getTransactions(): Observable<ITransactionResponse[]> {
    return this.httpClient.get<Result<ITransactionResponse[]>>(baseUrl + '/Transaction/GetTransactions')
    .pipe(map( res => res.data));
}

This is my Model:

export class ITransactionResponse {
    id: number;
    transactionNo?:string;
    valueDate?:Date;
    amount?: number;
}

EDIT:

enter image description here

Upvotes: 0

Views: 2456

Answers (2)

Fahad Subzwari
Fahad Subzwari

Reputation: 2325

Just replace this

getTransactions(): Observable<ITransactionResponse[]> {
    return this.httpClient.get<Result<ITransactionResponse[]>>(baseUrl + '/Transaction/GetTransactions')
    .pipe(map( res => {
           res.data.map(item => {
             item = new Date(item.valueDate)
           })
           return res.data;
     }));
}

To

getTransactions(): Observable<ITransactionResponse[]> {
    return this.httpClient.get<Result<ITransactionResponse[]>>(baseUrl + '/Transaction/GetTransactions')
    .pipe(map( (res : any) => res.data));
}

This is happening because you didn't specify the type of your incoming res and you are trying to access res.data.valueDate so compiler doesn't know the nested fields of res because default type of res is not an object

Upvotes: 1

Ramesh Shah
Ramesh Shah

Reputation: 321

After mapping the result to get list of ITransactionResponse, you can map the list of ITransactionResponse, like res.map(x => x.valueDate = new Date(x.valueDate))

Upvotes: 0

Related Questions