2

I'm trying to show data in my template coming from a json in the controller.

All the alternatives I found refers to using ngFor, but I don't want to iterate all the items, because I want to show just one of them.

getServicio(servicioId: number) {
        let getServicio = 'services?id=' + servicioId;
        this.http.getRequest(getServicio) //returns a json
            .then(
            res => {
                this.services = res[0];
            }
            )
            .catch(
            error => console.log(error)
            );
    }

And in the template I simply write:

{{services.id}}

It gives me an error:

Cannot read property 'id' of undefined

Isn't there any alternative to do it? Or in another way, passing all the data to the template and getting into the array with an index like:

{{services[0].id}}

Thanks in advance!

1
  • 1
    services is undefined while the HTTP response hasn't been received yet. Use ngIf to avoid displaying it while it's undefined, or use services?.id. BTW, why do you name it services if it's supposed to be a single service. And why does getRequest return an array, since you're passing the ID of the unique object to retrieve? Commented Nov 5, 2016 at 23:31

1 Answer 1

4

The problem is you are trying to display data (services.id) before it arrives (http requests are asynchronous) - which means services.id is undefined at the time the template is rendered. Simplest solution is to use safe navigation operator (?) to "protect" your template until data arrive:

{{services?.id}}

You can also use ngIf directive so the part of the template where you want to display services is not rendered until services is defined:

<div *ngIf="services">
    {{services?.id}}
</div>

Read more about safe navigation operator (?) here and more about ngIf directive here.

Sign up to request clarification or add additional context in comments.

Comments

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.