0

I have a service that returns an array of objects as an observable, a list of countries with objects with the country name and three-letter code, countries$ = this.mockData.get('countries.json');

If I have a 3-letter code for a country, I want to be able to filter the observable and return the matching name. For example if I have "GBR" I want to return "United Kingdom of Great Britain and Northern Ireland"

I have tried this,

  getfullCountryName() {
    const name = this.countries$.pipe(filter((c) => c.alpha3 === 'GBR'));
    console.log('name =', name);
    
    return name;
  }

but I must be forgetting something, since all I get in console is name = Observable {_isScalar: false, source: Observable, operator: FilterOperator}

What am I leaving off?

countries$ is a type of Country

export interface Country {
  numeric: string;
  alpha2: string;
  alpha3: string;
  name: string;
}

where should I put the type < > in that expression to get typings. e.g. that c has an attribute alpha3

4
  • 1
    you have to subscribe ...
    – enno.void
    Commented Aug 4, 2020 at 17:44
  • in your case, filter returns an observable and name receives an observable.
    – micronyks
    Commented Aug 4, 2020 at 17:59
  • so I try this an still nothing ` const name = this.countries$.pipe(filter((c) => c.alpha3 === 'GBR')).subscribe((x) => console.log(x));`
    – Steve
    Commented Aug 4, 2020 at 18:07
  • console.log(x) should display the result that you are looking for.....
    – micronyks
    Commented Aug 4, 2020 at 18:10

1 Answer 1

0

Filter returns an observable in your case which gets assigned to name;

getfullCountryName() {
    const name = this.countries$.pipe(filter((c) => c.alpha3 === 'GBR'));
      
    return name;  // returns observable
}

somewhere

this.getfullCountryName().subscribe(result=>console.log(result));  // will print the right result.

better version,
 getfullCountryName() {
    return this.countries$.pipe(filter((c) => c.alpha3 === 'GBR'));
}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.