1

I am trying to display Object in template . In console Users.email is working but in template its not working. Is it mandatory to define type of Users object. how to handle response properly.In console data is shown as object of users from which I am taking first object as data[0].

import { Component, OnInit } from '@angular/core';
import { Router }  from '@angular/router';
import { AuthenticationService } from './services/authentication.service';
import { EmployeeService }       from './services/emplyee.service';

@Component({
    template: `<h2>Welcome, {{ Users.email }}</h2>
    <button class="btn btn-info bg-blue bg-darken-2 mt-1 min-width-150" (click)="logout()"><i class="icon-unlock2"></i>
        Logout
    </button>`,
})
export class homeComponent implements OnInit {

    Users: any;

    constructor(private authenticationService: AuthenticationService,
                private router: Router, private
                emplyeeService: EmployeeService) {
    }

    ngOnInit() {
        if (!localStorage.getItem('currentUser')) {
            this.router.navigate(['/']);
            console.log("Go Login");
        } else {
            this.getUsers();
        }
    }

    logout() {

        this.authenticationService.logout();
        this.router.navigate(['/']);
    }

    getUsers() {
        this.emplyeeService.getAll()
            .subscribe(
                (data: any) => {
                    console.log(data);
                    this.Users = data[0];
                    console.log(this.Users.email);
                },
                (error) => console.log(error)
            );
    }
}
1
  • A side note. It is convention in TypeScript (and JavaScript) to use camelCase for local variables and field names. And to use PascalCase for classes and types. So Users -> users. Commented Apr 5, 2017 at 7:55

1 Answer 1

2

Your using Observables so the data will be little delay in time so you need to type safe opertaor ? as below

<h2>Welcome, {{ Users?.email }}</h2>
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any other solution? Like do I have to define type of user object?
yes exactly. you have to define a model. and then use it in your component

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.