在Angular2中访问Typescript对象变量 [英] Access Typescript Object Variables in Angular2

查看:202
本文介绍了在Angular2中访问Typescript对象变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何显示以下Hero对象的ID和标题? 下面的Hero接口是根据Firebase JSON响应映射的.

How do I display the id and title of the below Hero object? The Hero interface below is mapped according to Firebase JSON response.

hero.component.ts

import {Component, Input} from 'angular2/core';
import {Hero} from '../model/hero';

@Component({
  selector: 'hero-component',
  template: `
                {{hero | json }} this works. This display the Firebase JSON response as seen below 
                <br>
                {{ Object.keys(hero)[0] }} this DOESN'T work
                <br> 
                {{ hero[Object.keys(hero)[0]].title }}this also DOESN'T work
  `
})

export class HeroComponent {
  @Input()
  hero:Hero;
}

hero.ts

export interface Hero {
  [id: string]: {
    createdAt: number;
    isActive: boolean;
    title: string;
    updatedAt: number;
  }
}

Firebase JSON响应

{ "-KEMOfA5KFK98AXNhPY0": { "createdAt": 1459607745222, "isActive": true, "title": "Wind Hero", "updatedAt": 1459607745222 } } 

推荐答案

更新

而不是pipes: [KeysPipe]

使用

@NgModule({
  declarations: [KeysPipe],
  exports: [KeysPipe],
}
export class SharedModule{}

@NgModule({
  ...
  imports: [SharedModule],
})

原始

您不能在模板中使用Object.keys(hero)[0].不能使用全局引用,只能使用组件的成员.

You can't use Object.keys(hero)[0] in the template. No global references can be used, only members of the component.

而是在组件上创建一个函数

Instead create a function on your component

getKeys(obj) {
  return Object.keys(obj);
}

,然后在模板中

{{ getKeys(hero)[0] }}

或者,您可以构建一个提取键的管道,例如 https://stackoverflow.com/a/34074484/217408

Alternatively you can build a pipe that extracts the keys like for example https://stackoverflow.com/a/34074484/217408

@Pipe({ name: 'keys',  pure: false })
export class KeysPipe implements PipeTransform {
  transform(value: any, args: any[] = null): any {
    return Object.keys(value);
  }
}

然后像使用它

{{ (hero | keys)[0] }}

别忘了将管道添加到要使用它的组件上的pipes: [KeysPipe]上,或者另选

Don't forget to add the pipe to pipes: [KeysPipe] on the component where you want to use it or alternatively

bootstrap(App, [provide(PLATFORM_PIPES, {useValue: KeysPipe, multi:true})]);

这篇关于在Angular2中访问Typescript对象变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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