0

I am pretty new to angular 2, what I am trying to accomplish is simple:

  1. Get the category id passed in via routing
  2. Call API with category id
  3. Populate variable "category" with data returned from API and display the category name

My view is simple:

<h3>{{category.name}}</h3>

Component code:

import { Component, Inject } from '@angular/core';
import { Http } from '@angular/http';
import { ActivatedRoute } from '@angular/router';
@Component({
    selector: 'browse-category',
    template: require('./browse-category.component.html'),
    styles: [require('./browse-category.component.css')]
})
export class BrowseCategoryComponent {
    products: IProduct[];
    category: ICategory;
    categoryId: number;
    constructor(private route: ActivatedRoute, private http: Http, @Inject('ORIGIN_URL') private originUrl: string) {

    }

    ngOnInit(): void {
        this.route.params.subscribe(params => {
            this.categoryId = +params['categoryId']; 
            // get category details
            this.http.get(this.originUrl + '/api/Category/' + this.categoryId).subscribe(result => {
                var data = result.json().data;
                if (data != null && result.status === 200) {
                    this.category = data;
                    console.log(this.category);
                }
            });
        });
    }
}

If I disable the view output, i am able to see the console.log output, if I don't I get the following error:

NodeInvocationException: Uncaught (in promise): TypeError: Cannot read property 'name' of undefined TypeError: Cannot read property 'name' of undefined

I assume it's because the promise hasn't returned yet. Ideally what's the best approach to fix this?

1
  • What is the console.log output? Commented Sep 22, 2017 at 23:24

1 Answer 1

1

Use {{category?.name}} This is called the "safe navigation" operator and with it angular will only try to access category if it is defined and not null.

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

1 Comment

The Elvis operator is actually ?:. This is the "safe navigation" operator.

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.