我很困惑,因为我的应用程序正在显示必要的数据,但是控制台中仍然有一些我想摆脱的错误。
打字稿:
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;
}
答案 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});
}
}