Rens Groenveld
Rens Groenveld

Reputation: 982

Ionic 2 Angular 2 getting REST JSON data

I am probably just making a stupid mistake somewhere, but I just don't see it anymore.

I have a very simple Ionic 2 Angular 2 app. Please don't bother the architecture, I'm just trying to get it to work first. I am trying to fill my array 'configuredModules' with Module objects that I get from a REST JSON service. I have created a button which logs the array to the console, so I can see what the value of the array is, but is always undefined. What am I doing wrong?

export class Module {
    type: string;
    physicalLocationName: string;
}

and my main class:

import { Component, OnInit } from '@angular/core';
import { Module } from './module';
import { HttpModule, Http, Response} from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/toPromise';

import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage implements OnInit{
  configuredModules: Module[];
  http: Http;

  constructor(public navCtrl: NavController,private _http: Http) {
    this.http = _http;
  }

  getConfiguredModules(){
      this.getModules()
        .then(modules => this.configuredModules = modules);
        console.log('finished configuredModules');
  }

  getModules(): Promise<Module[]> {
    return       this.http.get('http://localhost:8080/rest/modules/configuredModules')
           .toPromise()
           .then(response => response.json().data as Module[])
          ;
  }

  ngOnInit() {
      this.getConfiguredModules();
  }

  buttonClicked(){
    console.log('button clicked');
    console.log(this.configuredModules.values);
  }
}

If I look in my network tab of Chrome, I can see the following coming in (under response):

{"modules":[{"type":"myTestType","physicalLocationName":"myTestPhysicalLocation"}]}

So I know the data is coming in, but it doesn't fill my array. Any suggestions? I think my code looks identical towards the Heroes tutorial of Angular 2: https://angular.io/docs/ts/latest/tutorial/toh-pt6.html

Upvotes: 1

Views: 755

Answers (1)

Fabio Antunes
Fabio Antunes

Reputation: 22862

Your error is in this function:

getModules(): Promise<Module[]> {
  return this.http.get('http://localhost:8080/rest/modules/configuredModules')
    .toPromise()
    .then(response => response.json().data as Module[]);
}

Remove the .data after the json() function and add .modules instead. That's what's coming from your API, so it should look like this:

getModules(): Promise<Module[]> {
    return this.http.get('http://localhost:8080/rest/modules/configuredModules')
           .toPromise()
           .then(response => response.json().modules as Module[]);
  }

Then on your button clicked function, remove the values, so it looks like this:

buttonClicked(){
  console.log('button clicked');
  console.log(this.configuredModules);
}

Upvotes: 2

Related Questions