-1

How to return only single value when services are injecting into the pipes?

This is the code of html file where i am using the pipe.

 {{model.template[i].locale | locale }}

Locale.pipe.ts file. when i console the result it prints only single value.bur does not return anything in html file.

import { Pipe, PipeTransform } from '@angular/core';
import { UserService } from '../../core/@services/user.service'

@Pipe({ name: 'locale' })
export class Locale implements PipeTransform {
 returnresponse: string;
 constructor(private UserService: UserService) { }
 transform(value: any) {
  this.UserService.lookupapi_code(value).subscribe(result => {
  console.log(result)
  //this.returnresponse = result;
   return result;
 });
// return this.returnresponse;
 }
}

User.service.ts file which return only single value from here

public lookupapi_code(languagecode): Observable<any> {
return this.http.get(AppSettings.lookupapi).map((response: Response) => {

  var Jstring = JSON.stringify(response);
  var Jarray = JSON.parse(Jstring);
  for (var i = 0; i < Jarray.length; i++) {
    if (Jarray[i].locale == languagecode) {
      return Jarray[i].displayName;
   }
  }
 });
}
swapnil jain
  • 252
  • 1
  • 3
  • 22
  • Possible duplicate of [angular 2 how to return data from subscribe](https://stackoverflow.com/questions/39295854/angular-2-how-to-return-data-from-subscribe) – Ingo Bürk Mar 27 '19 at 07:23

1 Answers1

2

Return an Observable from the pipe and chain "locale" with an Async pipe

@Pipe({ name: 'locale' })
export class Locale implements PipeTransform {
 returnresponse: string;
 constructor(private UserService: UserService) { }
 transform(value: any) {
  return this.UserService.lookupapi_code(value)
 }
}

HTML

{{model.template[i].locale | locale | async }}

Edit

Explanation for why it doesn't work for you:

Your case fails because: 1. You don't return anything 2. Even if you will return it won't be useful, read on..

someMethod() { <-- your transform
    someAsynBlock(() => {   <-- your subscribe
        return "result" <-- where will this return if you don't return the block itself? The block is asynchronous. 
    })
    // now don't mistakeen the above comment by returning the "someAsynBlock" 
    // because that will return a subscription Object which you can't use to retrieve the value
}

When you use async pipe you are subscribing the Observable in your template itself. https://angular.io/api/common/AsyncPipe#description

Also look for the side effects of using an async pipe but if you have to use your logic through a locale pipe then I don't see a way how you would do it without using an async pipe.

Ashish Ranjan
  • 12,760
  • 5
  • 27
  • 51