角度错误“无法读取未定义的属性'firstName'”

时间:2020-05-24 18:58:56

标签: html angular http elasticsearch get

嗨,我正在使用搜索服务来在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[];
}

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

1.SearchServiceComponent应该实现OnInit类并实现其ngOnInit方法 2.依次调用ngOnInit方法内的两个方法 3.检查this.user是否等于null或undefined并使用ngIf条件进行处理 萨吉塔兰回答

OnInit示例 TS

Test = transformType(Test);

答案 2 :(得分:0)

在您的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;
);
  }