0

I have the following Typescript service (app.component.ts):

import { Component, OnInit } from '@angular/core';
import { ApiService } from './shared/api.service';
import {PowerPlant} from './shared/models/powerplant.model';
import 'rxjs/add/operator/toPromise';

@Component({
  selector: 'app-root',
  providers: [ApiService],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  // represents the URL's
  allPowerPlantsURL = 'powerPlants';
  // represents the data
  powerPlants: PowerPlant[];

  ngOnInit(): void {
    this.allPowerPlants();
  }

  constructor(private apiService: ApiService) {
  }

  allPowerPlants(onlyActive: boolean = false, page: number = 1): void {
    const params: string = [
      `onlyActive=${onlyActive}`,
      `page=${page}`
    ].join('&');
    const path = `${this.allPowerPlantsURL}?${params}`;
    this.apiService.get(path)
    .toPromise()
    .then(elem => {
    console.log('In the allPowerPlants');
    console.log(elem); **// prints undefined here**
    this.powerPlants = <PowerPlant[]> elem; }
  )
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }
}

This is my app.component.html (just a snippet from it):

<div class="ui grid posts">
  <app-powerplant
    *ngFor="let powerPlant of powerPlants"
    [powerPlant]="powerPlant">
  </app-powerplant>
</div>

Now, in my powerplant.component.html, I have this:

import {Component, Input, OnInit} from '@angular/core'; import { PowerPlant } from '../shared/models/powerplant.model';

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

  @Input() powerPlant: PowerPlant;

  constructor() { }

  ngOnInit() {
  }
}

And finally, the one that is supposed to display the PowerPlant items are like this:

<div class="four wide column center aligned votes">
  <div class="ui statistic">
    <div class="value">
      {{ powerPlant.powerPlantId }}
    </div>
    <div class="label">
      Points
    </div>
  </div>
</div>
<div class="twelve wide column">
  <div class="value">
    MaxPower: {{ powerPlant.maxPower }} MinPower: {{ powerPlant.minPower }}
  </div>
  <div class="value">
    MaxPower: {{ powerPlant.maxPower }} MinPower: {{ powerPlant.minPower }}
  </div>
  <div class="value">
    PowerPlantType: {{ powerPlant.powerPlantType }} Organization: {{ powerPlant.powerPlantName }}
  </div>
</div>

I can see that the server is sending me the array as the following console log on the get method shows:

  get(path: string, params: URLSearchParams = new URLSearchParams()): Observable<any> {
    console.log('sending request to ' + `${environment.api_url}${path}`);
    return this.http.get(`${environment.api_url}${path}`, { search: params })
      .catch(this.formatErrors)
      .map((res: Response) => {
        console.log(res.json());
        res.json();
      });
  }

Where the line console.log prints me the following as seen in the screenshot:

enter image description here

So why is the toPromise() fails? Just for information, this is how my PowerPlant model looks like:

export interface PowerPlant {
  powerPlantId: number;
  powerPlantName: string;
  minPower: number;
  maxPower: number;
  powerPlantType: string;
  rampRateInSeconds?: number;
  rampPowerRate?: number;
}

2 Answers 2

1

Is there a specific reason to use the toPromise() method ? Does it work when subscribing normally ?

Try changing this

this.apiService.get(path)
  .toPromise()
  .then(elem => {
  console.log('In the allPowerPlants');
  console.log(elem); **// prints undefined here**
  this.powerPlants = <PowerPlant[]> elem; }
)

to this :

this.apiService.get(path).subscribe(result => {
    console.log('Im the result => ', result);
    this.powerPlants = <PowerPlant[]> result;
  });

Then it might be because you don't return the parsed result in your .map() method and thus you can't get the response in your promise / subscription.

.map((res: Response) => res.json()); // return is inferred in this syntax


.map((res: Response) => { 
  return res.json(); // here it's not
});
Sign up to request clarification or add additional context in comments.

4 Comments

Did not make much of a difference! This is what i get - Im the result => undefined
Updated answer, this might be it.
Yep! That was it! Cool! Thanks for the suggestion!
No problem ! Keep it going !
0

It is related to you your ApiService, you forgot to return res.json in your .map

  get(path: string, params: URLSearchParams = new URLSearchParams()): Observable<any> {
console.log('sending request to ' + `${environment.api_url}${path}`);
return this.http.get(`${environment.api_url}${path}`, { search: params })
  .catch(this.formatErrors)
  .map((res: Response) => {
    console.log(res.json());
    return res.json();
  });
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.