【问题标题】:Angular (click) method returns undefinedAngular(点击)方法返回未定义
【发布时间】:2019-12-02 22:02:39
【问题描述】:

所以我有一个组件,它显示了一个用户列表,当我点击它时,它应该打开用户详细信息视图。但是,根据当前代码,当我查看网络选项卡时,我看到由于某种原因使用未定义或姓氏、名字发出了 XHR 请求。

我的 Users.component.ts:

import { Component, OnInit } from '@angular/core';
import { AviorBackendService } from '../services/avior-backend.service';
import { UserCollection } from '../models/user-collection.model';
import { User } from '../models/user.model';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {

  selectedItem: string;

  users: UserCollection;
  user: User;
  firstname: string;
  selectedUser: User;

  constructor(private aviorBackend: AviorBackendService) { }

  ngOnInit() {
      this.aviorBackend.getUserCollection().subscribe(data => {
      // tslint:disable-next-line: no-string-literal
      this.users = data['firstname'];
      console.log(this.users);
      console.log("getUserCollection() Data: ", data);
    });
  }

  clickItem(firstname) {
      this.aviorBackend.getUser(firstname).subscribe(data => {
      // tslint:disable-next-line: no-string-literal
      this.selectedUser = data['user'];
      console.log(this.selectedUser);
      console.log("getUser() Data: ", data);
    });
  }
}

我的用户.component.html:

<div class="list-area">

  <div class="col-lg-12">

    <p class="list-header">Element overview</p>

    <div class="form-group">
      <label for="filter" class="lb-sm">Filter</label>
      <input type="text" class="form-control input-sm" name="filter" id="filter">
    </div>

   <select size="20" multiple class="form-control" id="elementlist" [(ngModel)]="selectedItem" (click)="clickItem(firstname)">
      <!-- maybe add | async pipe -->
    <option *ngFor="let user of users">
        {{user?.lastName}}, {{user?.firstName}}
      </option>
    </select>

  </div>

</div>

<div class="content-area">

  <div class="col-lg-12" *ngIf="selectedUser?.id">

  <p>Element contents {{selectedUser?.id}}</p>

  <div class="col-lg-12">
    <div class="form-group">
      <label for="firstName" class="lb-sm">First Name</label>
      <input type="text" class="form-control input-sm" name="firstName" id="firstName" [(ngModel)]="selectedUser.firstName">
    </div>
  </div>

  </div>

</div>

我的 getUser() 方法:

// Get user
  getUser(firstname: string): Observable<any> {
    const API_URL = `${SERVICE_URL}user/firstname/${firstname}`;
    return this.client.get(API_URL, this.httpOptions).pipe(
      map((res: Response) => {
        return res || {};
      }),
      catchError(this.handleError())
    );
  }

我的 user.model.ts:

import { Role } from './role';

// was class and not interface!
export interface User {
    _id: number;
    mandator?: number;
    loginId: string;
    lastname: string;
    firstname: string;
    password: string;
    eMail: string;
    group?: string;
    role?: Role;
    active?: boolean;
    token?: string;
}

我的 user-collection.model.ts:

import { User } from './user.model';

export interface UserCollection {

    user: User[];

}

我的 API 响应: https://imgur.com/a/f3owVEe

【问题讨论】:

  • 嗯,你有一个clickItem(firstname)。你打算打电话给clickItem(selectedItem.firstname)吗?
  • @DanielB 如果我将其更改为 clickItem(selectedItem.firstname) 我会收到以下错误:Identifier 'firstname' is not defined. '&lt;anonymous&gt;' does not contain such a member 而且它也不起作用
  • 您没有在clickItem() 函数中获得选定的名称,这会导致您的 API 失败,对吧??
  • 请问为什么在需要一个值时使用多个属性?
  • @Arcteezy 出于某种原因,对 API 的 XHR 请求包含“姓氏,名字”格式。多属性是什么意思?在哪一部分?

标签: angular xmlhttprequest


【解决方案1】:

如果我正确理解了问题,此更改将使其按照您的要求工作。

<select size="20" class="form-control" id="elementlist" [(ngModel)]="selectedItem" (change)="clickItem($event.target.value)">
    <option *ngFor="let user of users" value="{{user.firstname}}">
        {{user?.lastname}}, {{user?.firstname}}
    </option>
</select>

演示:https://stackblitz.com/edit/angular-yjma43

【讨论】:

  • 好答案!不应该有任何 click 处理程序,而应该只有 change 处理程序!
  • Identifier 'firstName' is not defined. 'User' does not contain such a member。如果我将其更改为名字,它仍然返回 undefined :/
  • 如果我更改它,我的列表会中断并且即使我更改了变量名称也不会被填充。此外,后端返回 firstname 而不是 firstName。
  • console.log("Print first name: ", this.firstname); 返回未定义
  • 不是 this.firstname。只需 firstname 这是您的函数参数。
【解决方案2】:

是的,你的代码是错误的。在你的 html 中试试这个:

 <option *ngFor="let user of users"  (click)="clickItem($event, user.firstName)" >
            {{user?.lastName}}, {{user?.firstName}}
          </option>

在你的 .ts 中你可以这样做:

clickItem(event, firstname)
{
  console.log("Print first name: ",firstname);
}

【讨论】:

  • ERROR ReferenceError: "firstname is not defined"
  • @i 编辑我的问题。尝试在您的 html 中使用 user.firstname
  • 他从哪里得到名字??
  • @Arcteezy 是的,你说得对,名字是未定义的,因为他在之后使用它。
  • @Doflamingo19 它仍然返回 undefined :/
猜你喜欢
  • 1970-01-01
  • 2015-06-22
  • 1970-01-01
  • 2016-11-08
  • 2017-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多