katzu
katzu

Reputation: 180

Angular 2 Pipe - can't return value inside a promise

I'm trying to do a really simple translate pipe for angular2. But I might be wrong how to promise work. The idea is to get the language parameter from a async service which call a doc in PouchDB. Fyi, the data are organised like this:

{
title: {
   fr: "text in french",
   en : "text in english",
...
}

The return inside the promise doesn't work. The html template is empty. I don't get why.

@Pipe({name: 'translate'})

export class Translate {

  lang:any;

  constructor(private interfaceService: Interface){}

  transform(obj) {

    this.interfaceService.getParams().then((data) => {
      return obj[data.language]
    }).catch((error) => {
      console.log(error);
    });

  }

}

If I put the return outside of the promise, it works:

@Pipe({name: 'translate'})

export class Translate {

  lang:any;

  constructor(private interfaceService: Interface){}

  transform(obj) {
   return obj.en

  }

}

Thanks for your help

Upvotes: 2

Views: 3743

Answers (1)

Tamas Hegedus
Tamas Hegedus

Reputation: 29916

You must return the resulting promise from the function.

export class Translate {
  // ...
  transform(obj) {
    return this.interfaceService.getParams().then((data) => {
      return obj[data.language]
    }).catch((error) => {
      console.log(error);
      throw error; // or `return Promise.reject(error);`
    });
  }
}

Upvotes: 3

Related Questions