【问题标题】:Angular2 Problems with service class and switchmapAngular2 服务类和 switchmap 的问题
【发布时间】:2016-12-15 08:56:56
【问题描述】:

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

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

这里是源代码:

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>

【问题讨论】:

  • 模板代码?
  • 您的模板在ngOnInit 之前编译,而您的componentType: ComponentType; 在初始级别未定义。

标签: json http angular


【解决方案1】:

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

您的解决方案之一是将模板代码包装在 &lt;template [ngIf]="yourObject"&gt;&lt;/template&gt; 中。

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

我更喜欢第一个。

【讨论】:

    猜你喜欢
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多