角度:无法读取未定义的属性,但仍显示数据

时间:2019-02-05 14:00:46

标签: angular

我很困惑,因为我的应用程序正在显示必要的数据,但是控制台中仍然有一些我想摆脱的错误。

打字稿:

  activeClient: Client;

  constructor(private clientService: ClientService) { }

  ngOnInit() {
    this.inViewMode = true;
    this.clientId = parseInt(window.location.pathname.split('/')[2], 10);
    this.clientService.getClientById(this.clientId)
        .subscribe(data => this.activeClient = data);
  }

HTML:

<div class="form-row">
   <div class="form-group col-12">
       <label for="name">Ettevõtte nimi<span *ngIf="!inViewMode" class="required">*</span></label>
       <input class="form-control" id="name" [value]="activeClient.companyName">
   </div>
</div>

客户端模型:

export interface Client {
    id?: number;
    companyName?: String;
    firmRegNo?: number;
    address?: String;
    clientName?: String;
    phoneOne?: number;
    phoneTwo?: number;
    email?: String;
    explanation?: String;
    rating?: number;
    status?: String;
    clientContract?: ClientContract;
}

3 个答案:

答案 0 :(得分:2)

通过对API进行activeClient调用来获取async的值。您的模板不会等到定义好之后。因此,您会在控制台上收到此错误。

activeClient块中初始化subscribe后,您确实会看到该值。

为避免这种情况,请在activeClient初始化之前不要渲染模板。

由于activeClient有很多字段,因此我建议使用*ngIf

<div class="form-row" *ngIf="activeClient">
   <div class="form-group col-12">
       <label for="name">Ettevõtte nimi<span *ngIf="!inViewMode" class="required">*</span></label>
       <input class="form-control" id="name" [value]="activeClient.companyName">
   </div>
</div>

(可选),您还可以在模板中使用async管道:

activeClient$: Observable<Client>;

constructor(private clientService: ClientService) {}

ngOnInit() {
  this.inViewMode = true;
  this.clientId = parseInt(window.location.pathname.split('/')[2], 10);
  this.activeClient$ = this.clientService.getClientById(this.clientId);
}

在您的模板中:

<div class="form-row" *ngIf="activeClient$ | async as activeClient">
   <div class="form-group col-12">
       <label for="name">Ettevõtte nimi<span *ngIf="!inViewMode" class="required">*</span></label>
       <input class="form-control" id="name" [value]="activeClient.companyName">
   </div>
</div>

答案 1 :(得分:2)

在呈现模板时,activeClient不存在(正在等待Observable提取数据)。使用elvis运算符进行安全显示。

[value]="activeClient?.companyName"

答案 2 :(得分:1)

使用safe navigation operator来防止错误,直到初始化{ "user" : { "Name":"Test", "Surname":"Test2", "Email":"example@example.com" }, "someData" : "If you like it, you put a data on it" } 为止:

[HttpPost]
public IActionResult CreateUser((User user, string someData) request)
{
    using (var db = new DBContext())
    {
        var newUser = db.Users.Add(request.user);
        db.SaveChanges();
        return Json(new { userId = request.user.Id, someData = request.someData});
    }
}