【问题标题】:Angular2 - Pipe converting enum form APIAngular2 - 管道转换枚举表单 API
【发布时间】:2016-06-22 07:52:31
【问题描述】:

我正在做一个项目,我想将后端枚举的 id 转换为字符串形式,以便前端更容易理解。

为此,我想使用管道。 管道应与 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;
    }
}

希望有人可以帮助或为我指明正确的解决方案。

____ 编辑:_____

作为一个新手,这是我从 Günter 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);
            });
        });
    }
}

【问题讨论】:

    标签: api pipe angular transform


    【解决方案1】:

    您不能让代码等待异步调用完成。

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

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

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

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

    【讨论】:

    • 感谢您的回答。我追随你的回答,但我现在得到一个空的结果。也许你可以看到我做错了什么。我将代码添加到问题中。
    • 我实现了一个简单的例子。 plnkr.co/edit/2LupLi?p=preview。似乎工作正常。需要| async 才能使其工作。
    • 我看到演示工作正常,但在 Promise 内似乎没有触发 HTTP。
    • 我更新了 Plunker plnkr.co/edit/d6iecn?p=preview(获取一些任意 URL)
    • 很好,我开始工作了,我不确定我到底做了什么,但它可以工作。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 2018-01-20
    • 2020-08-21
    • 2021-01-04
    • 2023-02-21
    • 2023-04-11
    • 1970-01-01
    相关资源
    最近更新 更多