user7024438
user7024438

Reputation:

How to obtain value of JSON array as a result of get Request?

How to obtain the value of JSON array as a result of getting Request?

   @Component({
     selector: 'app-navbar',
     templateUrl: './navbar.component.html',
    styleUrls: ['./navbar.component.css']
      })
     export class NavbarComponent implements OnInit {

    countries = ["Ukraine", "RSA"];
    data: Array<Country> = new Array();

      constructor(private http: HttpClient) { }

    ngOnInit(): void {

    this.http.get<Array<Country>>('http://localhost:8080/countries/db')
      .subscribe(data => {
        this.data = data;
      });

    console.log(this.data);
  }

}

JSON

[
  {
    "country": "Vatican-City"
  },
  {
     "country": "Zambia"
 },
 {
        "country": "Zimbabwe"
 }
]

I want to store the value of JSON as a string array in the data variable with Angular

Upvotes: 0

Views: 60

Answers (2)

FedG
FedG

Reputation: 1301

I'm not sure If I have understood:

this.http.get<Array<Country>>('http://localhost:8080/countries/db')
      .subscribe(data => {
        const countries = data;
        const countriesLis: Array<string> = new Array<string>()
        for( let country of countries) {
           countriesList.push(country);
         }
        this.data = countriesList;
      });

Upvotes: 1

Alejandro Santa-Cruz
Alejandro Santa-Cruz

Reputation: 51

Try stringify():

const data= { name: "John", age: 30, city: "New York" };
this.data = JSON.stringify(data);

Upvotes: 0

Related Questions