2

My utils service which returns the data from the mysql database using express framework

import { Injectable } from '@angular/core';
import { Http, HttpModule, Headers, RequestOptions } from '@angular/http';
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class UtilsService implements OnInit{
    public authData : any[];
    constructor(private http : Http) {
    }

    ngOnInit() { }

    getUserData() {
        const reqData = JSON.parse(localStorage.getItem('AuthUser'));
        return this.http.post('/get/logindata',reqData)
        .map(result => result.json().data);
    }
}

My Component Section

import { Component, OnInit } from '@angular/core';
import { UtilsService } from 'app/appservices/utils.service';

// Subscribers and mapping to get resutl
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Component({
    selector: 'app-navbar',
    templateUrl: './navbar.component.html',
    styleUrls: ['./navbar.component.scss']
})

export class NavbarComponent implements OnInit{
    result : any;
    constructor(private utils : UtilsService) {
        this.getLogData();
    }
    ngOnInit() {}

    getLogData() {
        this.utils.getUserData().subscribe(res=> this.result = res);
    }
}

HTML View

<div class="row">
<span>{{ result.DTP_User_Admin }}</span>
</div>

When ever i tried to bind the data in html it gives

ERROR TypeError: Cannot read property 'DTP_User_Admin' of undefined.

But the subscribe returns an object with value when i use console.log(this.result); am using Angular 5.2.9

ConnorsFan
  • 70,558
  • 13
  • 122
  • 146
YuvaMac
  • 419
  • 1
  • 6
  • 13

1 Answers1

5

The service returns the data asynchronously. The template is displayed before the data is available and the error happens when trying to access result.DTP_User_Admin while result is still undefined. Here are a few possible solutions:

Method 1 - Assign a default value when declaring result:

result = {};

Method 2 - Use the safe navigation operator:

{{ result?.DTP_User_Admin }}

Method 3 - Use *ngIf to display the element only when result is defined:

<span *ngIf="result">{{ result.DTP_User_Admin }}</span>
ConnorsFan
  • 70,558
  • 13
  • 122
  • 146
  • i have tried these methods nothing is bind in html view it prints only in console.log inside of getLogData() function. Is there any option to get data before the template view display – YuvaMac May 20 '18 at 04:41
  • @YuvaMac - Glad to hear that it works. Please mark the answer as accepted (with the green check mark). – ConnorsFan May 20 '18 at 12:19