无法使用 Angular 6 读取未定义的属性“名称”

Kri*_*s-I 1 asp.net-web-api typescript angular angular5 angular6

屏幕上显示的值是正确的,但我在日志中收到此错误:ERROR TypeError: Cannot read property 'name' of undefined

我用 '?' 尝试了几种方法 像这样: [(ngModel)]="customer?.name"但不起作用,那么我需要帮助:)

在服务中:

  getCustomer(name:string){
    let url = `http://localhost:8081/api/customer/${name}`;

    return this.http.get<Customer>(url);
  }
Run Code Online (Sandbox Code Playgroud)

在组件的 .ts 中:

customer: Customer;

this.customerService.getCustomer(this.pName)
      .subscribe(
        (data) =>{  
          this.customer = data['customer'];
        },
        err =>{
          console.log('getCustomer failed');
        }
    );
Run Code Online (Sandbox Code Playgroud)

在模板中:

<input type="text" class="form-control" id="myname" required [(ngModel)]="customer.name" name="myname">
Run Code Online (Sandbox Code Playgroud)

但这不行。

你有想法吗 ?

谢谢,

Ras*_*ari 6

添加默认值

public customer = {} as Customer;
Run Code Online (Sandbox Code Playgroud)

和这个

 <input type="text" class="form-control" id="myname" required [(ngModel)]="customer?.name" name="myname">
Run Code Online (Sandbox Code Playgroud)

  • 给出一个默认值将解决这个问题,不确定你这边发生了什么,确保你不仅仅是定义而是分配给一个空对象,就像这个 public customer = {} as Customer; (2认同)