Angular2服务类和switchmap

时间:2016-12-15 08:56:57

标签: json http angular

我目前在使用Angular 2时遇到了一些问题。我习惯于为我的一个数据库组件创建一个详细视图。

到目前为止一切都很好。我的JSON服务正在按预期提供数据。 当我在subscribe函数中调试我的结果时,似乎没问题,但是模板崩溃说“无法读取未定义的内容......”

以下是源代码:

import 'rxjs/add/operator/switchMap';
import {Component, OnInit} from "@angular/core";
import {ActivatedRoute, Params} from "@angular/router";
import { Location } from '@angular/common';

import {ComponentTypeService} from "./component-type.service";
import {ComponentType} from "./database_objects";

@Component({
  moduleId: module.id,
  selector: 'component-type-detail',
  templateUrl: 'component-type-detail.component.html'
})

export class ComponentTypeDetailComponent implements OnInit{
  componentType: ComponentType;
  constructor(
    private componentTypeService: ComponentTypeService,
    private route: ActivatedRoute,
    private location: Location,
  ) {}

  ngOnInit(): void {
      this.route.params
        .switchMap((params: Params) => this.componentTypeService.getComponentTypeDetails(+params['id']))
        .subscribe(comp => {
          this.componentType = comp;
          console.log(comp);
        });
  }

  goBack(): void {
    this.location.back();
  }
}

这是服务代码:

import { Injectable } from '@angular/core';
import {ComponentType} from "./database_objects";
import {Http, Headers} from "@angular/http";

import 'rxjs/add/operator/toPromise';

@Injectable()
export class ComponentTypeService{
  private baseUrl = 'http://127.0.0.1:8080/myFirstApp/component-types/'

  constructor(private http: Http) {}
  getComponentTypes(): Promise<ComponentType[]>{
    return this.http.get(this.baseUrl)
      .toPromise()
      .then(response => response.json().results as ComponentType[])
      .catch(this.handleError);
  }

  getComponentTypeDetails(id: number): Promise<ComponentType>{
    const url = `${this.baseUrl}${id}/`;
    return this.http.get(url)
      .toPromise()
      .then(response => response.json() as ComponentType)
      .catch(this.handleError);
  }

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

Error Stack in Browser. Please look at the bottom. The object is defined in line 31 it is inside the subscribe function

更新

感谢您的所有答案。这个模板缺少一个* ngIf =“componentType” 这是更新的模板:

<div *ngIf="componentType">
  <h2>{{componentType.component_type_name}} details!</h2>
  <div>
    <label>id: </label>{{componentType.id}}
  </div>
  <div>
    <label>name:</label>
    <!--<input [(ngModel)]="componentType.component_type_name" placeholder="name" />-->
  </div>
  <div *ngIf="componentType.components">
    <ul>
      <li *ngFor="let component of componentType.components">
        {{component}}
      </li>
    </ul>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

问题是您的模板在定义之前尝试访问该对象。

您的解决方案之一是将模板代码包装在<template [ngIf]="yourObject"></template>

另一种解决方案是在尝试访问对象属性的任何地方添加*ngIf

我更喜欢第一个。