user11352561
user11352561

Reputation: 2647

Angular - ERROR TypeError: Cannot read property 'title' of undefined

I am calling Laravel Endpoints into Angular 7. I have two table smsmo and package. smsmo has package_id as a foreign key from package(id). I want to display title instead of package_id. I got this error in my console.

error

angular

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>

The issue is in

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

I want to display title from package(id, title) instead of package_id in smsmo (id, package_id) What do I do.

Every other thing is working fine apart from this.

Upvotes: 2

Views: 1186

Answers (1)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24434

it seem the package is undefined that why you got this error

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

or you can use ng-container with ngIf directive to check package object

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

Upvotes: 1

Related Questions