You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular下拉选择器返回[object Object]而非实际值问题求助

Angular下拉选择器显示[object Object]问题解决

问题描述

我有一个从服务拉取数据的Angular下拉选择器,当选择任意选项时,控制台输出如下内容:

{enterprises: '[object Object],[object Object],[object Object],[object Object]', warehouses: ''}

其中enterprises为可选企业,warehouses为可选仓库。同时在另一页面头部展示选中值时,也显示为[object Object]。

相关代码

Dashboard组件HTML

<div>
  <select class="form-select" formControlName="enterprises" (change)="updateSelectValues()">
    <option value="" disabled selected="selected">SELECCIONA LA EMPRESA</option>
    <option [value]="enterprises" *ngFor="let item of enterprises">{{item.name}}</option>
  </select>
</div>
<div style="margin-top: 10px">
  <select class="form-select" aria-label="Default select example" formControlName="warehouses"
    (change)="updateSelectValues()">
    <option value="" disabled selected="selected">SELECCIONA EL TALLER</option>
    <option [value]="item" *ngFor="let item of warehouses">{{item.name}}</option>
  </select>
</div>

Dashboard组件TS

import { Component, Input, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { DatosService, EmpresaTaller } from '../services/datos.service';
import { ApiService } from '../services/api.service';

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

  token = "";
  userName = "";
  error = "";

  enterprise=-1;
  warehouse=-1;

  enterprises = [];
  warehouses = [];

  seleccionado;

  selectForm: FormGroup;

  cargaCount = 0;
  cargaTrasiego = 0;
  descargaCount = 0;
  descargaTrasiego = 0;

  constructor(
    private datosService: DatosService, 
    private fb: FormBuilder, 
    private api:ApiService,
  ) { }

  ngOnInit() {
    this.token=sessionStorage.getItem('authToken');
    this.userName=sessionStorage.getItem('userName');

    this.api.getEnterprises(this.token, this.userName).subscribe(responseEnterprises=>{
      const {result, value} = responseEnterprises;
      if(result !== 0 || !value || !value.Rows || value.Rows.length === 0){
        this.error='Error, usuario sin empresas';
        return;
      }
      this.enterprises=value.Rows.map(enterprise=>{
        const {CODIGO: code, EMPRESA: name} = enterprise;
        return {code, name};
      });
      this.enterprise = this.enterprises[0].code;


      this.api.getWarehouses(this.token, this.userName, this.enterprise).subscribe(responseWarehouses=>{
        const {result, value} = responseWarehouses;
        if(result !== 0 || !value || !value.Rows || value.Rows.length === 0){
          this.error='Error, usuario sin almacenes';
          return;
        }
        this.warehouses=value.Rows.map(warehouse=>{
          const {CODIGO: code, ALMACEN: name} = warehouse;
          return {code, name};
        });
        this.warehouse = this.warehouses[0].code;

        this.api.getDashboard(this.token, this.userName, this.enterprise, this.warehouse).subscribe(responseDashboard=>{
          const {result, value} = responseDashboard;
          if(result !== 0 || !value || !value.Rows || value.Rows.length === 0){
            this.error='Error, no ha devuelto dashboard';
            return;
          }
          this.cargaCount = value.Rows[0].orden_carga_count;
          this.cargaTrasiego = value.Rows[0].orden_carga_trasiego_count;
          this.descargaCount = value.Rows[0].orden_descarga_count;
          this.descargaTrasiego = value.Rows[0].orden_descarga_trasiego_count;
        });

      });

    });

    this.selectForm = this.fb.group({
      enterprises: [''],
      warehouses: ['']
    });
  }

  updateSelectValues() {
    this.datosService.updateEmpresaTaller(this.selectForm.value as EmpresaTaller);
  }

}

Header组件HTML

<header class="sticky-top">
  <nav class="navbar navbar-expand-lg navbar-dark bg-dark" style="overflow: hidden">

    <div class="container-fluid">
      <div>
        <div>
          <div class="badge bg-primary text-wrap">
            <p>{{(datosEmpresaTaller | async).enterprises}}</p>
          </div>
        </div>
        <div style="margin-top: 10px">
          <div class="badge bg-primary text-wrap">
            <p>{{(datosEmpresaTaller | async).warehouses}}</p>
          </div>
        </div>
      </div>

      <form class="d-flex">
        <button class="btn btn-outline" type="submit" routerLink='/dashboard'> <img src="assets/icons/menu.png"
            alt="Cerrar Sesión" height="100" width="120" /></button>
      </form>

    </div>
  </nav>
</header>

Header组件TS

import { Component, OnInit } from '@angular/core';
import { DatosService, EmpresaTaller } from '../services/datos.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css'],
})
export class HeaderComponent implements OnInit {
  datosEmpresaTaller: Observable<EmpresaTaller>;

  constructor(private datosService: DatosService) {}

  ngOnInit(): void {
    this.datosEmpresaTaller = this.datosService.getEmpresaTaller();
  }
  
}

DatosService服务

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

export interface EmpresaTaller {
  enterprises: string,
  warehouses: string
}

@Injectable({
  providedIn: 'root'
})
export class DatosService {
  private selectValues = new BehaviorSubject<EmpresaTaller>({enterprises: '', warehouses: ''});

  constructor() { }

  updateEmpresaTaller(values: EmpresaTaller) {
    this.selectValues.next(values);
    console.log(values)
  }

  getEmpresaTaller() {
    return this.selectValues.asObservable();
  }
}

问题原因

  1. 企业下拉框绑定错误:HTML中企业选项的[value]绑定的是整个enterprises数组,而非当前循环的item。选择时表单控件会把数组转成字符串,导致输出[object Object],...。
  2. 对象转字符串显示:仓库下拉框绑定的是item对象,而[value]只能处理字符串,Angular会自动把对象转成[object Object]字符串。
  3. 接口类型不匹配:EmpresaTaller接口定义enterprises和warehouses为string类型,但实际传递的是对象,类型不匹配进一步导致显示异常。

解决方案

1. 修正企业下拉框的绑定值

把企业选项的[value]="enterprises"改成[value]="item"(如需传递整个对象)或[value]="item.name"(如需仅传递名称):

<option [value]="item" *ngFor="let item of enterprises">{{item.name}}</option>

2. 使用[ngValue]绑定对象(推荐)

Angular的select控件中,[ngValue]支持绑定对象,避免自动转字符串的问题:

<!-- 企业下拉框 -->
<option [ngValue]="item" *ngFor="let item of enterprises">{{item.name}}</option>

<!-- 仓库下拉框 -->
<option [ngValue]="item" *ngFor="let item of warehouses">{{item.name}}</option>

3. 调整接口类型

如果传递的是对象,更新EmpresaTaller接口:

export interface EmpresaTaller {
  enterprises: {code: string, name: string},
  warehouses: {code: string, name: string}
}

4. Header组件中正确显示属性

在Header组件中,需要访问对象的name属性来显示,同时用?.避免空值报错:

<p>{{(datosEmpresaTaller | async).enterprises?.name}}</p>
<p>{{(datosEmpresaTaller | async).warehouses?.name}}</p>

内容的提问来源于stack exchange,提问作者Miriam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 14:41:45