#angular
#angular
Вопрос:
Ниже приведен фрагмент кода метода getClients() clientsService приложения angular. Речь идет о преобразовании поля _id массива коллекций данных, полученных из MongoDB, только в поле id — используется в модели Angular.
Пожалуйста, обратитесь к самому внутреннему оператору возврата, где я преобразую массив клиентов, изменяя поле _id объекта ответа только полем id — в соответствии с моделью клиента Angular. Есть ли способ написать этот оператор map без перезаписи полей, которые не меняются.
getClients() {
this.http.get<{message: string, clients: any}>('http://localhost:3000/api/clients')
.pipe(map((clientData) => {
return clientData.clients.map(client => {
return {
// is there a better way of writing the below part. I just need to transform only one field.
id: client._id,
compName: client.compName,
title: client.title,
fName: client.fName,
lName: client.lName,
addr1: client.addr1,
addr2: client.addr2,
city: client.city,
state: client.state,
pincode: client.pincode
};
});
}))
.subscribe(mappedClients => {
this.clients = mappedClients;
this.clientsUpdated.next([...this.clients]);
// emitting a copy of clients array and not the original array
});
}
Ответ №1:
Используя оператор распространения javascript, вы можете изменить, как показано ниже.
getClients() {
this.http.get<{ message: string, clients: any }>('http://localhost:3000/api/clients')
.pipe(map((clientData) => {
return clientData.clients.map(client => {
const object = { ...client };
object.id = client._id;
delete object._id;
return object;
});
}))
.subscribe(mappedClients => {
this.clients = mappedClients;
this.clientsUpdated.next([...this.clients]);
// emitting a copy of clients array and not the original array
});
}