angular: Elvis Operator fail with object that Arrary?
Hi, I was creating an example that recive a json from public Api, the json’s structure is:
{
"success": {
"total": 1
},
"contents": {
"quotes": [
{
"quote": "Never waste your time trying to explain who you are to people who are committed to misunderstanding you.",
"length": "104",
"author": "Dream Hampton",
"tags": [
"inspire",
"misunderstanding",
"tso-life",
"tso-management",
"wasting-time"
],
"category": "inspire",
"date": "2016-01-31",
"title": "Inspiring Quote of the day",
"background": "https://theysaidso.com/img/bgs/man_on_the_mountain.jpg",
"id": "OVmnzpHewxSTCw3AXDgnpweF"
}
]
}
}
But in my template when I try to use elvis operator It fails. I got the error
EXCEPTION: TypeError: Cannot read property ‘0’ of null in [{{quote?.contents?.quotes[0]?.quote}} in App@4:20]
import {Component, OnInit, Injectable} from 'angular2/core';
import {Http, HTTP_PROVIDERS, URLSearchParams} from 'angular2/http';
import 'rxjs/add/operator/map';
@Component({
selector: 'app',
template: `<ul>
<li (click)='myAlert()'> Helow World</li>
</ul>
<div>
<spam>{{quote?.contents?.quotes[0]?.quote}}</spam>
</div>`,
providers: [HTTP_PROVIDERS]
})
export class App {
public quote: Object;
public logError: string;
constructor(private http: Http){
this.quote = {};
}
myAlert(){
this.http.get("http://quotes.rest/qod.json").map(res => { return res.json()})
.subscribe(
data => this.quote = data,
err => this.logError(err),
() => console.log('Random Quote Complete')
);
}
}
It failed because I’m trying to use an Elvis operator with an object that has an array. It works perfect with nested objects without array. I’m missing something??
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Reactions: 1
- Comments: 16 (6 by maintainers)
It works this way
It is sad though that
quotes?[0]
isn’t supported yet nor(quotes || [])[0]
It might be expected to not work atm, but probably it makes sense to support it as new feature
works as expected
You probably would need a
to only access the first item only when
quotes != null && quotes.length > 0
. I don’t use TS/JS but I guess this doesn’t exist.