Fatih
Fatih

Reputation: 53

Angular 6 Waiting service response before render template

I can't resolve this problem. Anybody know what happens here?

My CategoryService is

  getCategory(): Observable<Category[]> {
    // return this.http.get<Category[]>("/category");

    return this.http.get<Category[]>(this.endpoint)
  }

And here is my edit-category component

    import { Component, OnInit } from '@angular/core';
import { CategoryService, Category } from '../services/category.service';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-edit-category',
  templateUrl: './edit-category.component.html',
  styleUrls: ['./edit-category.component.scss']
})
export class EditCategoryComponent implements OnInit {

  constructor(private categoryService : CategoryService, private router: ActivatedRoute ) { }
  category : Category;

  ngOnInit() {
    this.router.params.subscribe(params => {
          this.categoryService.getCategory().subscribe((data : Category[]) => {

            this.category = data.filter(res => {
              return res.id == params["id"]
            })[0];
            console.log(this.category)

          });
   });

  }

}

I need to call category in my edit-category-component.html .

<p>
  {{category.Adi}}
</p>

I can do this but after that or meanwhile browser says 4 times (I have 4 record) . But my code showing after that 4 errors record. Code works, so how these mistakes are made.

ERROR TypeError: Cannot read property 'Adi' of undefined

I'm new at angular. This is looks like promise or ngOnInit? And sorry I realy dont know How can I write true question.

Upvotes: 1

Views: 1200

Answers (1)

user184994
user184994

Reputation: 18281

You can use the null safe operator instead:

<p>
  {{category?.Adi}}
</p>

This will prevent the error you're seeing when category is null / undefined. You can read more here: https://angular.io/guide/template-syntax#the-safe-navigation-operator----and-null-property-paths

Upvotes: 2

Related Questions