在渲染模板之前的Angular 6等待服务响应

时间:2018-05-06 20:07:31

标签: angular

我无法解决此问题。有谁知道这里发生了什么?

我的CategoryService是

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

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

这是我的编辑类别组件

    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)

          });
   });

  }

}

我需要在edit-category-component.html中调用类别。

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

我可以做到这一点,但之后或浏览器说4次(我有4条记录)。但我的代码显示在4个错误记录之后。代码有效,所以这些错误是如何产生的。

ERROR TypeError: Cannot read property 'Adi' of undefined

我是角色的新人。这看起来像promise还是ngOnInit? 抱歉,我真的不知道我怎么能写出真正的问题。

1 个答案:

答案 0 :(得分:2)

您可以使用null safe运算符:

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

这可以防止您在类别为nu​​ll / undefined时看到的错误。您可以在此处阅读更多内容:https://angular.io/guide/template-syntax#the-safe-navigation-operator----and-null-property-paths

相关问题