Search code examples
angularangular5angular6angular-servicesangular-module

Getting error in Displaying value coming from service in Angular


I have a service in Key:value or in countryCode : countryName pair

Servicve ->

{"BD": "Bangladesh", "BE": "Belgium", "BF": "Burkina Faso", "BG": "Bulgaria", "BA": "Bosnia and Herzegovina", "BB": "Barbados", "WF": "Wallis and Futuna", "BL": "Saint Barthelemy", "BM": "Bermuda", "BN": "Brunei", "BO": "Bolivia", "BH": "Bahrain", "BI": "Burundi", "BJ": "Benin", "BT": "Bhutan", "JM": "Jamaica"}

I have created an Interface to receive value from the service

interface

export interface IcounrtyCode {
    code: string;
    country: string;
}

which is probably creating problem in receiving the value the way I want

if you see my response when I write console.log( this.counrtyCode) It displays like ->

AD: "Andorra" AE: "United Arab Emirates" AF: "Afghanistan" AG: "Antigua and Barbuda" AI: "Anguilla" AL: "Albania"

where AD is key and Andorra is value. Maybe If I can able to change response in following way. {[code:"AD",country:"country"]} then I can catch the response in my way , I tried to do so But I am getting error How I can do that ..?


Solution

  • You probably want to create yourself a sort of Dictionary interface

    interface Dict {
        [key: string]: string;
    }
    

    You should be able to map your response to that.

    The issue you have is that you are trying to map your object to your IcounrtyCode interface but the json returned from the service is not in the correct shape. It would need to be something like the below:

    {["code": "BD", "country":"Bangladesh"]}
    

    I would recommend changing the server response to the correct json format if you have control over the server code.