EXCEPTION:未捕获(在承诺中):由以下原因引起的错误:无法读取未定义的属性“名称”

时间:2017-02-08 09:20:11

标签: angular

我是Angular2的新手。当我尝试将此代码添加到camp.detail.component.html(对于detail /:id API视图)时,

{{campDetail.campground.name}}

它始终显示以下错误消息:

error1

error2

当我删除

{{campDetail.campground.name}}

然后没有错误消息,我们可以看到对象是在控制台中打印的:

error3

我做了很多搜索并尝试了尽可能多的解决方案,但仍然没有找到解决此问题的正确方法。 (例如:Angular 2 router Error: Uncaught (in promise): TypeError: Cannot read property 'resolve' of undefinedUncaught (in promise): Error: Cannot read property of undefinedAngular 2 Uncaught (in promise): TypeError: Cannot read property 'isActivated' of undefinedhttps://github.com/angular/angular/issues/8519

如何解决此异常?任何建议对我都有帮助和有用。我真的很感激。

我的文件如下:

campgrounds.service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Campground } from "../models/campground";
import { Comment } from "../models/comment";

export class CampDetail {
    campground: Campground;
    comments: Comment[];
}

@Injectable()
export class CampgroundService {
    private campgroundsUrl = 'api/campground';
    constructor(private http: Http) { }

    getCamps(): Promise<Campground[]> {
        return this.http.get(this.campgroundsUrl)
            .toPromise()
            .then(response => response.json())
            .catch(this.handleError);
    }

    getCamp(id: number): Promise<CampDetail> {
        return this.http.get(this.campgroundsUrl + '/' + id)
            .toPromise()
            .then(response => response.json())
            .catch(this.handleError);
    }

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

campground.ts

export class Campground {
    id: number;
    name: string;
    image: string;
    description: string;
    username: string;
    user_id: number;
}

comment.ts

export class Comment {
    id: number;
    text: string;
    campground_id: number;
    username: string;
    user_id: number;
}

camp.detail.component.ts

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

import { CampgroundService, CampDetail } from "../../services/campgounds.service";

@Component({
    selector: 'campDetail',
    templateUrl: './app/components/campgrounds/camp.detail.component.html'
})

export class CampDetailComponent implements OnInit {
    error: any;
    campDetail: CampDetail = new CampDetail();

    constructor(
        private campgroundService: CampgroundService,
        private route: ActivatedRoute) {
    }

    ngOnInit() {
        this.route.params
            .switchMap((params: Params) => this.campgroundService.getCamp(params['id']))
            .subscribe(data => {
                this.campDetail = data;
                console.log(this.campDetail);
            });
    }
}

campground.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { CampgroundService } from "../../services/campgounds.service";
import { Campground } from "../../models/campground";

@Component({
    selector: 'camps',
    templateUrl: './app/components/campgrounds/campgrounds.component.html',
    styleUrls: ['./app/components/campgrounds/campgrounds.component.css']
})

export class CampgroundsComponent implements OnInit {
    camps: Campground[];

    constructor(private router: Router, private campService: CampgroundService) { }

    getCamps() {
        this.campService.getCamps().then(camps => this.camps = camps);
    }
    ngOnInit() {
        this.getCamps();
    }

    gotoDetail(id: number) {
        this.router.navigate(['/detail', id]);
    }
}

奇怪的是当我在campground.component中使用getCamps()调用campground API时,一切正常。点击按钮后

<button class="btn btn-primary" (click)="gotoDetail(camp.id)"> More Info </button> 

并指向另一个页面,我会收到此错误。

1 个答案:

答案 0 :(得分:4)

由于您的campDetail数据是异步加载的,并且在创建组件时不可用,因此您需要检查其嵌套属性&#39;使用Angular safe navigation operator的路径:

{{campDetail?.campground?.name}}