![](/img/trans.png)
[英]Angular 6 - ERROR TypeError: Cannot read property 'firstName' of undefined, While showing the output
[英]Angular error “Cannot read property 'firstName' of undefined”
嗨,我正在開發搜索服務以在 elasticsearch 數據庫中查找用戶名,但是當我想顯示用戶的 fe 名字時出現以下錯誤:無法讀取未定義的屬性“名字”。
我正在使用 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的Output:
用戶界面:
export interface User {
$oid: string;
firstName: string;
lastName: string;
username: string;
password: string;
follows: User[];
}
我猜 getObject() 在您加載表單時被調用,此時用戶未定義,因此您收到該錯誤。 為什么你不只使用 user?.firstName ,因為你已經定義了變量?
<p>{{user?.firstName}}</p>
1.SearchServiceComponent 應實現 OnInit class 並實現其 ngOnInit 方法 2. 依次調用 ngOnInit 方法內部的兩個方法 3. 檢查 this.user 是否不等於 null 或 undefined 並使用 ngIf 條件進行處理
OnInit TS 示例
@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnInit {
ngOnInit() {
this.getUser();
this.getObject()
}
getUser() {
const userName = this.angForm2.value.searchText;
console.log(this.angForm2.value, userName);
this.searchservice.getElasticResult(userName).subscribe(user => (this.user = user.hits.hits[0]._source));
}
getObject(){}
}
在你的 html 你需要做這樣的事情
<p>{{usersFirstName}}</p>
在您的 ts 代碼中,一旦您從服務器獲得響應,請設置此 usersFirstName。
usersFirstName : string;
getUser() {
const userName = this.angForm2.value.searchText;
console.log(this.angForm2.value, userName);
this.searchservice.getElasticResult(userName).subscribe(user => (this.user = user)
this.usersFirstName = user.name;
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.