首页 > 解决方案 > Angular 6在渲染模板之前等待服务响应

问题描述

我无法解决这个问题。有人知道这里发生了什么吗?

我的 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 中调用 category 。

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

我可以这样做,但在那之后或者同时浏览器说 4 次(我有 4 条记录)。但是我的代码在那 4 个错误记录之后显示。代码有效,那么这些错误是如何产生的。

ERROR TypeError: Cannot read property 'Adi' of undefined

我是角度的新手。这看起来像 Promise 还是 ngOnInit?对不起,我真的不知道我怎么能写出真正的问题。

标签: angular

解决方案


您可以改用 null 安全运算符:

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

这将防止您在类别为空/未定义时看到的错误。您可以在此处阅读更多信息:https ://angular.io/guide/template-syntax#the-safe-navigation-operator----and-null-property-paths


推荐阅读