角度-错误TypeError:无法读取未定义的属性“标题”

时间:2019-06-21 13:04:50

标签: angular laravel

我将Laravel端点称为Angular7。我有两个表smsmo和包。 smsmo将package_id作为package(id)的外键。我想显示标题而不是package_id。我在控制台中收到此错误。

error

角度

smsmo.ts

import { User } from '../models/user';
import { Telco } from '../models/telco';
import { Package } from '../models/package';

export class Smsmo {
    id: number;
    msisdn: string;
    message: string;
    short_code_called: string;
    packaged_id: string;
    error_message: string;
    error_code: string;
    telco: string;
    user_id: number;

    user?: User;
    telcoId?: Telco;
    package?: Package;

    constructor() {}
}

package.ts

import { User } from '../models/user';
import { Services } from '../models/services';

export class Package {
    id: number;
    title: string;
    descriptions: String;
    price: string;
    days: number;
    service_id: number;
    key_word: string;
    welcome_message: string;
    amount: string;
    user?: User;

    service?: Services;
    constructor() {}
}

smsinbox.component.ts(smsmo)

export class SmsInboxComponent implements OnInit {

    smsmos: Smsmo[];
    isLoading: Boolean = false;
    public searchText: string; 
    public filter: string;  

    constructor(private smsmoService: SmsmoService) { }

    ngOnInit() {

        // Get Bulk SMS Inbox detail
        this.getSmsmos();    

        window.dispatchEvent(new Event('resize'));

        document.body.className = 'skin-blue sidebar-mini';
    }

    ngOnDestroy(): void {
        document.body.className = '';
    }

     getSmsmos(): void {
         this.isLoading = true;
         this.smsmoService.getSmsmos()
            .subscribe(
                response => this.handleResponse(response),
                error => this.handleError(error));
            }
}

smsinbox.component.html

<tr  *ngFor="let smsmo of smsmos; let i = index">
    <td>{{i + 1}}</td>
    <td>{{smsmo.msisdn}}</td>
    <td>{{smsmo.short_code_called}}</td>
    <td>{{smsmo?.package['title']}}</td>
    <td>{{smsmo.error_message}}</td>
    <td>{{smsmo.error_code}}</td>

</tr>

问题出在

  

{{sssmo?.package ['title']}}

我想显示来自package(id,title)的标题,而不是smsmo(id,package_id)中的package_id 我该怎么办。

除此之外,其他所有功能都可以正常工作。

1 个答案:

答案 0 :(得分:1)

该软件包似乎是未定义的,您为什么会收到此错误

 <td>{{smsmo?.package?.title || 'Not available' }}</td>

或者您可以将ng-container与ngIf指令一起使用以检查包对象

<ng-container *ngIf="smsmo?.package; else default ">
    <td>{{smsmo?.package.title}}</td>
</ng-container>
<ng-template #default>
    <td> Not available </td>
</ng-template>