gpt4 book ai didi

html - 未定义的 Angular 错误 “Cannot read property ' firstName'”

转载 作者:行者123 更新时间:2023-12-03 01:17:07 25 4
gpt4 key购买 nike

嗨,我正在使用搜索服务在Elasticsearch数据库中查找用户名,但是当我想显示f.e时出现以下错误。用户的名字:无法读取未定义的属性“名字”。

我正在使用Angular和Elasticsearch

服务:

export class SearchService {

getElastic = 'http://34.62.28.281:9200/users/_doc/_search?q=';
private handleError: HandleError;

constructor(
private http: HttpClient,
httpErrorHandler: HttpErrorHandler) {
this.handleError = httpErrorHandler.createHandleError('TimelineService');
}
/** GET elasticsearch result */
getElasticResult( text: string ): Observable<User> {
this.http.get<User>(this.getElastic + text).subscribe(res => console.log(res));
return this.http.get<User>(this.getElastic + text, {responseType: 'json'});

}

编辑:
新的HTML表单:
<form [formGroup]="angForm2" *ngIf="user != null" (ngSubmit)="getUser()" class="form-inline my-5 my-lg-0">
<input id="searchText" name="searchText" class="form-control" type="string" placeholder="Search for user" aria-label="Post"
formControlName="searchText" required>
<p>{{user?.firstName}}</p>
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>

新组件:
export class SearchServiceComponent implements OnInit {
user: User;
angForm2 = this.fb.group({
searchText: ['', Validators.required]
});

ngOnInit() {
this.getUser();
this.getObject();
}

constructor(private searchservice: SearchService, private fb: FormBuilder) { }

getUser() {
const userName = this.angForm2.value.searchText;
console.log(this.angForm2.value, userName);
this.searchservice.getElasticResult(userName).subscribe(user => (this.user = user));
}
getObject() {
return this.user;
}
}

用户和this.user的输出:

enter image description here

用户界面:
export interface User {
$oid: string;
firstName: string;
lastName: string;
username: string;
password: string;
follows: User[];
}

最佳答案

我猜想在加载表单时会调用getObject(),此时用户未定义,所以您会收到该错误。为什么不只使用user?.firstName,因为您已经定义了变量?

  <p>{{user?.firstName}}</p>

关于html - 未定义的 Angular 错误 “Cannot read property ' firstName'”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61990945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com