【问题标题】:EXCEPTION: Uncaught (in promise): Error caused by: Cannot read property 'name' of undefined例外:未捕获(承诺中):错误导致:无法读取未定义的属性“名称”
【发布时间】:2017-02-08 09:20:11
【问题描述】:

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

{{campDetail.campground.name}}

它总是出现以下错误信息:

当我删除时

{{campDetail.campground.name}}

那么就没有错误信息了,我们可以在控制台看到对象打印出来了:

我进行了多次搜索并尝试了尽可能多的解决方案,但仍然找不到解决此问题的合适方法。 (例如: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() 调用露营地 API 时,一切正常。点击按钮后

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

然后转到另一个页面,我会收到此错误。

【问题讨论】:

    标签: angular


    【解决方案1】:

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

    {{campDetail?.campground?.name}}
    

    【讨论】:

    • 现在可以正常使用了!!!真的很感激。我花了一整天的时间试图解决这个问题......
    猜你喜欢
    • 2023-03-31
    • 2020-05-13
    • 1970-01-01
    • 2018-06-03
    • 2021-04-18
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    相关资源
    最近更新 更多