0

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?

3
  • hi, could you please tell in detail again? what is your exact problem? Commented Apr 10, 2019 at 7:07
  • If you tried something and it didn't work, then post what you tried, tell precisely what you expected to happen, and what happened instead. Commented Apr 10, 2019 at 7:09
  • 1
    I updated my question. Commented Apr 10, 2019 at 7:46

2 Answers 2

3

Use the rxjs map operator with Array.prototype.map().

  1. 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.

  2. 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
);
Sign up to request clarification or add additional context in comments.

1 Comment

@Nastaran Heydari, you have to return the result from the inner map, in my example I am using an implicit return. Also your inner map does not return anything, use forEach in that case
1

If this is only for display purposes, you should just do

{{email.Notification.Subject || '(No Subject)'}}

If not, go for mapping the array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.