首页 文章

来自承诺的角度 4 显示元素

提问于
浏览
0

我有以下的 Typescript 服务(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);
  }
}

这是我的 app.component.html(只是它的一个片段):

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

现在,在我的 powerplant.component.html 中,我有这个:

从'@angular/core'导入{Component,Input,OnInit};进口{。 5}来自'../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() {
  }
}

最后,应该显示 PowerPlant 项目的那个是这样的:

<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>

我可以看到服务器正在向我发送数组,因为 get 方法显示以下控制台日志:

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();
      });
  }

在 console.log 行打印我的内容如截图所示:

在此输入图像描述

那么为什么 toPromise()失败了?仅供参考,这就是我的 PowerPlant 模型的样子:

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

2 回答

  • 1

    是否有使用toPromise()方法的特定原因?正常订阅时是否有效?

    尝试改变这个

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

    对此:

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

    那么可能是因为您没有在.map()方法中返回解析后的结果,因此您无法在您的承诺/订阅中获得响应。

    .map((res: Response) => res.json()); // return is inferred in this syntax
    
    .map((res: Response) => { 
      return res.json(); // here it's not
    });
    
  • 0

    它与您的 ApiService 有关,您忘记在.map中返回res.json

    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();
      });
    }
    

相关问题