Reputation: 165
I have an angular app and in one of the components I'm getting user's notifications(Emails) via a service. the service returns an array of Objects and in each object there's information of an email like subject , userid of the sender, etc. the structure of array of email object is like this:
[{
UserId:"...",
Notification:{
Subject:null,
Body:"<div>...</div>",
.
.
.
},
.
.
.
},
.
.
.]
some emails don't have subject and the value of Subject
property is null
in the object. I want to set a value for emails with Subject:null
.
this.notifService.getAllNotificationsForCurrentUser(userId)
.pipe(
map(emails => {
emails.map(email=>{
if(email.Notification.Subject === null){
email.Notification.Subject = "(No Subject)";
}
})
}
)
.subscribe(
result=> this.messages = result
);
I used map
operator and it doesn't work. and it has some errors:
Cannot read property 'Notification' of undefined
how can I fix it?
Upvotes: 0
Views: 3341
Reputation: 15566
If this is only for display purposes, you should just do
{{email.Notification.Subject || '(No Subject)'}}
If not, go for mapping the array.
Upvotes: 1
Reputation: 13963
Use the rxjs map operator with Array.prototype.map().
The first map
allows you to modify the array of emails as if flows down the stream. It maps over the stream elements, each element is an array of emails.
The second map
changes the array of emails to set the empty subject
fields to no subject
. It maps over the emails array, each element is an email.
import { map } from 'rxjs/operators';
this.notifService.getAllNotificationsForCurrentUser(userId).pipe(
map(emails => {
return emails.map(email => ({
...email,
Notification: {
...Notification,
Subject: email.subject ? email.subject : 'no subject'
}
}));
})
).subscribe(
result=> this.messages = result
);
Upvotes: 3