顺便说一下,我是Typescript和Angular2的新手.
我有一个返回类型为PracticeTestList的对象的服务.服务和对象的声明如下所示.
现在,我有一个读取对象的自定义管道,如下所示.
自定义管道类确实收到了对象,但在for循环中,对象被读取为单行字符串而不是对象.这是为什么?
如何在Typescript中将对象作为对象读取?
谢谢
服务
getMyPracticeTest(uid: string){ return this._http.get('http://localhost:49753/RestServiceImpl.svc/getMyPracticeTest/' + uid) .map(data => { data.json(); // the console.log(...) line prevents your code from working // either remove it or add the line below (return ...) console.log("getMyPracticeTest >>>>>>> ",data.json()); return data.json(); }); }
对象声明
import { Injectable } from '@angular/core'; @Injectable() export interface PracticeTestList { Purchase_ID: number; User_FK: number; name: string; price: number; resteurant: string; credit_card_number: string; purchase_date : any; Test_Status_FK: number; child :string; }
定制管道
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({name: 'values'}) export class ValuesPipe implements PipeTransform { transform(value, args:string[]) : any { let keys = []; for (let key in value) { console.log("Key >>>> " + key + " value >>>>> " + value[key]); keys.push({key: key, value: value[key]}); } return keys; } }
在管道内添加了Log
Key >>>> 0 value >>>>> [ main.bundle.js:64502:13 Key >>>> 1 value >>>>> { main.bundle.js:64502:13 Key >>>> 2 value >>>>> " main.bundle.js:64502:13 Key >>>> 3 value >>>>> P main.bundle.js:64502:13 Key >>>> 4 value >>>>> u main.bundle.js:64502:13 Key >>>> 5 value >>>>> r main.bundle.js:64502:13 Key >>>> 6 value >>>>> c main.bundle.js:64502:13 Key >>>> 7 value >>>>> h main.bundle.js:64502:13 Key >>>> 8 value >>>>> a main.bundle.js:64502:13 Key >>>> 9 value >>>>> s main.bundle.js:64502:13 Key >>>> 10 value >>>>> e main.bundle.js:64502:13 Key >>>> 11 value >>>>> _ main.bundle.js:64502:13 Key >>>> 12 value >>>>> I main.bundle.js:64502:13 Key >>>> 13 value >>>>> D main.bundle.js:64502:13 Key >>>> 14 value >>>>> " main.bundle.js:64502:13 Key >>>> 15 value >>>>> : main.bundle.js:64502:13 Key >>>> 16 value >>>>> 1 main.bundle.js:64502:13 Key >>>> 17 value >>>>> , main.bundle.js:64502:13 Key >>>> 18 value >>>>> "
添加了HTML代码
Key: {{entry.key}}, value: {{entry.value}} |
Günter Zöchb.. 5
使用Object.keys
先拿到钥匙:
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'values' }) export class ValuesPipe implements PipeTransform { transform(value): any { let keys = Object.keys(value); return keys.map(k => value[k]); } }
您可以尝试Object.values()
直接获取值,但可能无法在任何地方获得支持.
使用Object.keys
先拿到钥匙:
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'values' }) export class ValuesPipe implements PipeTransform { transform(value): any { let keys = Object.keys(value); return keys.map(k => value[k]); } }
您可以尝试Object.values()
直接获取值,但可能无法在任何地方获得支持.