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

Angular+TypeScript问题:API返回结果无法赋值给类型化变量

问题:Angular中API返回数据赋值后属性全为undefined

问题背景

我近期开始学习Angular和TypeScript,正在构建一个调用本地HR数据Web API的测试应用。已通过Fiddler确认API返回了预期数据集,数据正常。但将返回结果赋值给Employee接口实例后,所有属性均为undefined,无报错。

相关代码与数据

1. Employee接口定义

export interface Employee {
    department: string;
    departmentId: number;
    email: string;
    employeeId: number;
    firstName: string;
    hireDate: string;
    jobId: number;
    lastName: string;
    manager: string;
    managerId: number;
    phoneNumber: string;
    salary: number;
    title: string;
}

2. API返回数据格式

[{…}]
0
: 
department
: 
null
departmentId
: 
6
email: "bruce.ernst@sqltutorial.org"
employeeId
: 
5
firstName: "Bruce"
hireDate: "5/21/1991"
jobId
: 
9
lastName: "Ernst"
manager
: 
null
managerId
: 
2
phoneNumber: "590.423.4568"
salary
: 
6000
title
: 
null
[[Prototype]]: Object
length: 1
[[Prototype]]: Array(0)

3. EmployeeService代码

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ActivatedRoute } from '@angular/router';
import { Employee } from '../Interfaces/employee';
import { Observable, of, throwError } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})

export class EmployeeService {

  constructor(private http: HttpClient,
    private route: ActivatedRoute) {     
  }

  getEmployeeById(id: number): Observable<Employee> {
    const employee = this.http.get<Employee>("http://localhost:200/api/Employee/GetEmployeeById?id=" + id);
    return employee;
  }
}

4. EmployeeDetail组件代码

import { Component, OnInit, Input } from '@angular/core';
import { Employee } from '../Interfaces/employee';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { EmployeeService } from '../services/employee.service';

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

  @Input() employee?: Employee;

  constructor(private route: ActivatedRoute,
    private employeeService: EmployeeService,
    private location: Location) { }

  ngOnInit(): void {
    this.getEmployee();
  }

  getEmployee(): void {
    const id = Number(this.route.snapshot.paramMap.get('id'));
    this.employeeService.getEmployeeById(id)
      .subscribe(e => { 
        console.log(e);  
        this.employee = e;        
      });
  }

  goBack(): void {
    this.location.back();
  }
}

问题现象

在console.log(e)行,浏览器开发者工具能看到预期的数值,但执行this.employee = e赋值后,this.employee的所有属性均为undefined,且无任何报错。

解决方案

核心问题是API返回的是包含单个Employee对象的数组,而非单个对象,但服务方法声明返回的是Observable<Employee>(单个对象),导致类型不匹配。

方案1:修改服务方法处理数组

在服务中通过map操作符从返回的数组中提取第一个元素:

getEmployeeById(id: number): Observable<Employee> {
  return this.http.get<Employee[]>("http://localhost:200/api/Employee/GetEmployeeById?id=" + id)
    .pipe(
      map(employees => employees[0]) // 提取数组中的第一个员工对象
    );
}

方案2:在组件回调中处理数组

如果不想修改服务,也可以在组件的subscribe回调中直接处理返回的数组:

.subscribe(employees => { 
  console.log(employees);  
  this.employee = employees[0];        
});

两种方案都能正确将API返回的数组中的对象赋值给this.employee,解决属性undefined的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:45:41