2016-03-08 48 views
1

我正在一个项目中,我想要将enum窗体后端的id转换为字符串窗体,以便更容易理解forntend。Angular2 - 管道转换枚举窗体API

为此我想使用管道。 管道应该通过API获取带有键和值的JSON对象。

我的问题是,我似乎无法得到转换函数等待,直到我收到api数据并将其存储在一个变量中。

我知道如何联系API并获取对象。我做了一个转变,做到了我需要它做的事情。我无法将我的头围绕在如何让两个人一起谈话。

这里是我现在:

import {Pipe, PipeTransform} from 'angular2/core'; 

import {ApiHelper} from '../../services/api.service'; 

@Pipe({ name: 'userType' }) 
export class userType implements PipeTransform { 

    private typeObject; 

    constructor(private ApiService: ApiHelper) { 
     ApiService.getAllTypes().subscribe(
      types => this.storeTypes(types) 
     ); 
    } 

    storeTypes(types){ 
     this.typeObject = types; 
    } 

    transform(value: number, args: string[]): any { 
     var userType; 

     for(var type in this.typeObject){ 
      if(type.value == value){ 
       usertype = type.key; 
      } 
     } 

     return userType; 
    } 
} 

希望有人能帮助或点我朝着正确的解决方案。

____编辑:_____

作为一个新手,这是我从君特Zöchbauer的回答理解。 这不会返回我的观点。

import {Pipe, PipeTransform} from 'angular2/core'; 

import {ApiHelper} from '../../services/api.service'; 

@Pipe({ name: 'userType' }) 
export class userType implements PipeTransform { 

    constructor(ApiService: ApiHelper) 

    transform(value: number, args: string[]): any { 

     return new Promise((resolve, reject) => { 
      this.ApiService.getAllTypes().subscribe(typeObject => { 

       var userType; 
       for (var type in typeObject) { 
        if (type.value == value) { 
         usertype = type.key; 
        } 
       } 

       resolve(userType); 
      }); 
     }); 
    } 
} 

回答

0

您无法让代码等待完成异步调用。

我还没有尝试过构建这样一个管道,它自己会返回一个promise,但是如果它可以工作,那么返回一个在值到达时完成的Promise。

transform(value: number, args: string[]): any { 
    return new Promise((resolve, reject) => { 
    http.get(...).map(...).subscribe(value => { 
     ... 
     resolve(theResult); 
    }); 
    }); 
} 

除了自定义管道之外,您可能还需要使用async管道。

<div>{{item | userType | async}}</div> 
+0

谢谢你的答案。我按照你的答案打结,但我现在只能得到一个空的结果。也许你可以看到我做错了什么。我将我的代码添加到问题中。 – Habber

+0

我实现了一个简单的例子。 https://plnkr.co/edit/2LupLi?p=preview。似乎工作正常。 '|异步'是必需的,使其工作。 –

+0

我看到演示的作品,但似乎HTTP不被解雇时,无极里面。 – Habber