【问题标题】:Angular service promise first is undefined [duplicate]Angular服务承诺首先是未定义的[重复]
【发布时间】:2016-10-09 02:28:21
【问题描述】:

今天我从 Angular 2 开始,已经遇到了一个我无法解决的错误。

我有一个“opdracht”服务,它正在从模拟文件中加载数据。 opdracht 组件是 home 组件的 4 倍。第一个未定义,后三个正在显示。

我认为这个承诺有问题。但我不知道是什么。代码和控制台错误在这里。

我做错了什么?

谢谢,

马丁

控制台错误

main.bundle.js:41251EXCEPTION: Uncaught (in promise): Error: Error in ./OpdrachtComponent class OpdrachtComponent - inline template:0:3 caused by: Cannot read property 'name' of undefined

opdracht.ts

export interface Opdracht {
  id: number;
  name: string;
}

opdracten.mock.ts

import { Opdracht } from "./opdracht";

export const OPDRACHTEN: Opdracht[] = [
  {
    id: 1,
    name: "Apple iDrive"
  },
  {
    id: 2,
    name: "Lunchroom Bakker"
  },
  {
    id: 3,
    name: "Augmented Albert"
  },
  {
    id: 4,
    name: "Pecha Kucha"
 }
];

opdracten.service.ts

import {Injectable} from "@angular/core";
import {Opdracht} from "./opdracht";
import {OPDRACHTEN} from "./opdrachten.mock";

@Injectable()
export class OpdrachtenService {

  getOpdracht(id: any): Promise<Opdracht> {
    return Promise.resolve(OPDRACHTEN[id]);
  }
}

opdracht.component.ts

import {Component, OnInit, Input} from "@angular/core";
import {OpdrachtenService} from "../services/opdrachten/opdrachten.service";
import {Opdracht} from "../services/opdrachten/opdracht";

@Component({
  selector: 'app-opdracht',
  templateUrl: './opdracht.component.html',
  styleUrls: ['./opdracht.component.scss'],
  providers: [OpdrachtenService]
})
export class OpdrachtComponent implements OnInit {

  @Input() private id: any;

  protected opdracht: Opdracht;

  constructor(private opdrachtenService: OpdrachtenService) { }

  getOpdracht(): void {
    this.opdrachtenService.getOpdracht(this.id)
      .then((opdracht: Opdracht) => {
        this.opdracht = opdracht
      })
    ;
  }

  ngOnInit() {
    this.getOpdracht();
  }
}

opdracht.component.html

<p>{{ opdracht.name }}</p>

home.component.html

<app-header></app-header>
<app-foto></app-foto>
<app-ik></app-ik>
<app-opdracht [id]="0"></app-opdracht>
<app-opdracht [id]="1"></app-opdracht>
<app-opdracht [id]="2"></app-opdracht>
<app-opdracht [id]="3"></app-opdracht>
<app-footer></app-footer>

【问题讨论】:

  • 您正在调用 id 为 0 的 opdracht,但您的模拟文件中没有它。
  • 输入名称“id”有点误导。我用它作为索引。

标签: angular typescript service promise


【解决方案1】:

当 Angular 评估绑定但异步值尚未到达时,使用安全导航运算符避免错误:

<p>{{ opdracht?.name }}</p>

【讨论】:

  • 谢谢。这解决了问题!
  • 很高兴听到:)
猜你喜欢
  • 2015-08-12
  • 2017-03-01
  • 1970-01-01
  • 2016-08-17
  • 1970-01-01
  • 2021-11-01
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多