简体   繁体   English

如何在angular 2模板打字稿中显示json对象参数

[英]How to display json object parameters in angular 2 template typescript

I am trying to display Object in template . 我正在尝试在template中显示Object。 In console Users.email is working but in template its not working. 在控制台中, Users.email运行正常,但在模板中却无法运行。 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]. 如何在控制台中正确处理响应。在控制台中,数据显示为用户的对象,而我将第一个对象作为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)
            );
    }
}

Your using Observables so the data will be little delay in time so you need to type safe opertaor ? 您使用的是Observables,因此数据的时间延迟很小,因此您需要输入安全操作符? as below 如下

<h2>Welcome, {{ Users?.email }}</h2>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM