1

In app.component.ts I receive data via API:

export class AppComponent implements OnInit{

 constructor(private http: HttpClient){}
 items: Object;
  getApi(){
   return this.http.get("https://reqres.in/api/user");
  }
ngOnInit(){
  this.getApi().subscribe( data => {
    this.items = data
    console.log(this.items)
  })
 }
}

In my app.component.html I output that data:

<ul *ngIf="items">
   <li *ngFor="let item of items.data">
      {{ item.id }} {{ item.name }} {{ item.year }}
   </li>
</ul>

My question is, whether you can change the id with a string connected to the integer of the id. For example id = 1 => 1 means string "one" , id = 2 => means string "two".

Sadly I do no know how to change the value of the received data with a new value.

I hope it is clear what I want to achieve, if not do not hesitate to ask!

I hope you can help me. Thank you!

2
  • You want to change numbers to words? Commented Dec 25, 2018 at 23:17
  • @Oen44 Correct, it is just an example for a real project. Commented Dec 25, 2018 at 23:18

2 Answers 2

3

If you know all the values you want to map, you could create a dictionary in your component which would take care of the mapping.

myMap = {
    1: "one",
    2: "two"
};

and then in your HTML

<ul *ngIf="items">
   <li *ngFor="let item of items.data">
      {{ myMap[item.id] }} {{ item.name }} {{ item.year }}
   </li>
</ul>
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! Looks like it is the solution I need. I will test it! ~ It worked, thank you!
Now create hundreds or thousands.
I agree with Oen44. This is definitely not the way to go if you want to have more than a couple of "known" mappings.
@Oen44 It is just an example. I do not have the real API, but that is exactly what I needed. Thank you both!
1

number-to-words will do the trick. You won't have to worry about coding names yourself.

var converter = require('number-to-words');

ngOnInit(){
  this.getApi().subscribe( data => {
    this.items = data;
    this.items.forEach((item, index) => {
        this.items[index].id = converter.toWords(item.id);
    })
  })
 }

1 Comment

Thank you! I keep it in mind in case I will need it but I think mapping is the right way to go because later I will have only 6 cases and for every case there is only one value. I did not have any API so I had to take one on the internet, so the question might be a little confusing. ~ Please forgive me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.