Reputation: 1426
I have created a starter dictionary for my Angular 6 app...
import { Injectable } from "@angular/core";
@Injectable()
export class Languages {
//template (in English)
public dialect = {
"Vocab": [{
"Pg1": {
"tag1": "my first string",
"tag2": "my second string",
"tag3": "my third string"
}
}, {
"Pg2": {
"tag1": "my fourth string",
"tag2": "my fifth string",
"tag3": "my sixth string"
}
}, {
"Pg3": {
"tag1": "my seventh string",
"tag2": "my eighth string",
"tag3": "my nineth string"
}
}, ]
}
}
When I type this in the calling component...
console.log(this.languages.dialect.Vocab[0].Pg1.ta
...it auto completes the tag I choose for me--in this case I select "tag2". So I know it all works right. When I run the app, the console shows the string "my second string".
All good
However... when I backtrack, and type "Vocab[0].Pg2.ta" it still auto completes for me, but when I choose any value other than Pg1, I get the following error...
ERROR TypeError: "this.languages.dialect.Vocab[0].Pg2 is undefined"
No errors show in the IDE, and the app compiles just fine. What am I doing wrong?
Upvotes: 1
Views: 58
Reputation: 757
this.languages.dialect.Vocab[0].Pg2
must be this.languages.dialect.Vocab[1].Pg2
.
You can rewrite your code like this for easier access:
// this.languages.dialect.Vocab.Pg2
public dialect = {
"Vocab": {
"Pg1": {
"tag1": "my first string",
"tag2": "my second string",
"tag3": "my third string"
}, "Pg2": {
"tag1": "my fourth string",
"tag2": "my fifth string",
"tag3": "my sixth string"
}, "Pg3": {
"tag1": "my seventh string",
"tag2": "my eighth string",
"tag3": "my nineth string"
}
}
}
Upvotes: 1
Reputation: 3040
Change your dialect to this
//template (in English)
public dialect = {
"Vocab": [{
"Pg1": {
"tag1": "my first string",
"tag2": "my second string",
"tag3": "my third string"
},
"Pg2": {
"tag1": "my fourth string",
"tag2": "my fifth string",
"tag3": "my sixth string"
},
"Pg3": {
"tag1": "my seventh string",
"tag2": "my eighth string",
"tag3": "my nineth string"
}
} ];
Or use
this.languages.dialect.Vocab[1].Pg2
Upvotes: 1
Reputation: 8277
Try this.languages.dialect.Vocab[1].Pg2
Your Pg2
document is the second element of the parent array.
Upvotes: 0