如何在angular 2模板打字稿中显示json对象参数 [英] How to display json object parameters in angular 2 template typescript

查看:151
本文介绍了如何在angular 2模板打字稿中显示json对象参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在template中显示Object.在控制台中, Users.email 正在运行,但在模板中却无法运行.定义用户对象的类型是否是强制性的?如何在控制台中正确处理响应.在控制台中,数据显示为用户的对象,而我将第一个对象作为data [0].

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)
            );
    }
}

推荐答案

您使用Observables,因此数据的时间延迟很小,因此您需要按以下方式键入安全操作符 ?

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>

这篇关于如何在angular 2模板打字稿中显示json对象参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆