Skip to content
Advertisement

How to access array elements in angular

From an API, I’m trying to get data using httpModule. Here is my code

async searchMeaning(form: NgForm) {

    const post = {
      word: form.value.inputWord,
      language: form.value.language
    }
    console.log(post);
    if (post.language && post.word) {
       this.output1 = await this.callApi(post); // it displays await has not effect
       console.log(this.output1) // undefined.
    }
  }

   callApi(post) {
    this.http.get('https://api.dictionaryapi.dev/api/v2/entries/'+post.language+'/'+post.word)
    .subscribe((data) => {
      console.log(JSON.parse(JSON.stringify(data)));
      return data;
      
    }, (error : any) => {
      return error
    })
  }

When I use async and await, it says that await has no effect. An undefined is getting assigned to the variable this.output. How can I make this work? Also, How can I get access to a variable from the below response array?

[
    {
        "word": "hello",
        "phonetics": [
            {
                "text": "/həˈloʊ/",
                "audio": "https://lex-audio.useremarkable.com/mp3/hello_us_1_rr.mp3"
            },
            {
                "text": "/hɛˈloʊ/",
                "audio": "https://lex-audio.useremarkable.com/mp3/hello_us_2_rr.mp3"
            }
        ],
        "meanings": [
            {
                "partOfSpeech": "exclamation",
                "definitions": [
                    {
                        "definition": "Used as a greeting or to begin a phone conversation.",
                        "example": "hello there, Katie!"
                    }
                ]
            },
            {
                "partOfSpeech": "noun",
                "definitions": [
                    {
                        "definition": "An utterance of “hello”; a greeting.",
                        "example": "she was getting polite nods and hellos from people",
                        "synonyms": [
                            "greeting",
                            "welcome",
                            "salutation",
                            "saluting",
                            "hailing",
                            "address",
                            "hello",
                            "hallo"
                        ]
                    }
                ]
            },
            {
                "partOfSpeech": "intransitive verb",
                "definitions": [
                    {
                        "definition": "Say or shout “hello”; greet someone.",
                        "example": "I pressed the phone button and helloed"
                    }
                ]
            }
        ]
    } ]

here I need to get the value of the definition variable from the above array. How can I do that?

console image

Advertisement

Answer

When I use async and await, it says that await has no effect.

Yes, that’s because await only has an effect on Promises (a type native to Javascript). this.callApi(post) returns a Subscription (which is a RxJS type), which isn’t the same as a Promise.

In Angular, I’d argue that using Promises is an antipattern (unless required by a third party library). Instead you should use Observables and subscribe to them, which you’ll find out later has a tons of advantages in more complex situations. The way you usually do this is by building up observables with pipes as far as possible, and then subscribe when you actually need to do the call, like this:

searchMeaning(form: NgForm) {

    const post = {
      word: form.value.inputWord,
      language: form.value.language
    }
    console.log(post);
    if (post.language && post.word) {
       this.callApi(post).subscribe(x => {
           this.output1 = x;
           console.log(this.output1); // shouldn't be undefined anymore
           // if you want to do more to
           // affect the state of the component, 
           // you can do it here
       });
       // Be cautious, things that you write here will actually execute before the call to the API.
    }
  }

   callApi(post) {
    this.http.get('https://api.dictionaryapi.dev/api/v2/entries/'+post.language+'/'+post.word)
    .pipe(map(x => {
         // if you want to change x in some way 
         // before returning to the calling method, 
         // you can do it here
         return x;
     }));
  }

Also, How can I get access to a variable from the below response array?

For example, if you want to access the first definition example, you could do the following: x[0]["meanings"][0]["definitions"][0]["example]. You could also make a type definition to make it even easier to access, but it’s probably not worth it if you’re just using the dictionary for a few things.

It can be worthwhile to look through the Angular docs on Observables, or at least look at the concrete use cases with calling APIs with HttpClient

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement