简体   繁体   中英

Using Elvis Operator within String Interpolated Expressions in Angular 2

In my Angular 2 app I am using string interpolation to pull data from a mongoDB. Right now the server/database in in flux, so on occasion that will break my client-side display because, for instance, if I am pulling in data via string interpolation, like this:

{{record.addresses[0].zipCode}}

... and then, at a later time, the way the data is organized in the database changes, this will break my display - because the client is trying to pull in from fields that are no longer there. So I think I should be able to use something like the elvis operator in a use case like this. That way, if the data is where the client is looking for it, it will print out to the screen. But, if the data is not where it's looking for it, it will just ignore the field altogether - not breaking anything in the display.

So, in short, how would I implement the elvis operator on an expression like I have above?

You use it like this:

{{record?.addresses[0]?.zipCode}}

This will check if record is defined then if addresses[0] is defined under record object and then if zipCode is defined under that object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM