【问题标题】:Unable to fetch response using subscribe in Angular无法在 Angular 中使用订阅来获取响应
【发布时间】:2020-04-12 07:07:00
【问题描述】:

我正在尝试获取响应并将其分配给 subscribe 方法中的变量,然后使用该变量来检索和使用获取的数据。以下是我的代码:

API:

public IHttpActionResult GetData(string empID)
{
    empID = empID ?? " ";

    try
    {
        using (var connection = new OracleConnection(ConfigurationManager.ConnectionStrings["Database"].ConnectionString))
        {
            IRepository repository = new RepositoryClass(connection);
            DataCollection employee = new DataCollection();

            employee.employeeData = repository.GetData(empID).ToList();
            employee.CountInResponse = employee.employeeData.Count;

            if (employee.employeeData != null && employee.CountInResponse > 0) {
                return Ok (employee) 
            }
            else
                return Content(HttpStatusCode.NotFound, "No Employee data found for this request");
        }
    }
    catch (Exception ex)
    {
        return CreateLevel3Exception(ex);
    }
}

组件:

UpdateEmployee()
{
    this.getEmployeeData()

    if(
        this.EmployeeOrigData.EmployeeID == this.newID
        && this.EmployeeOrigData.EmployeeName == this.newName
        && this.EmployeeOrigData.EmployeeContact == this.newContact
        && this.EmployeeOrigData.EmployeeStatus == this.newStatus
        && this.EmployeeOrigData.EmployeeAddress == this.newAdress
    )
    {
        this.Message('info', 'Update invalid');
    }
}


getEmployeeData() {
    this.service.GetEmployeeData(this.addEmployeeID)
        .subscribe((response) => 
        {
            this.EmployeeOrigData = response;
        },
        (err) => 
        {
            if (err == '404 - Not Found')
              this.Message('info', err, 'Update Unsuccessful - Server error');
            else
              this.Message('error', 'Error', err);
        });
}

服务:

GetEmployeeData(empID: string) {
    debugger;
    let params = new URLSearchParams();
    params.set('empID',empID)
    debugger;
    return this.http.get(Url, { params: params })
          .map(res => res.json().employeeData)
          .catch(this.handleError);
}

这里我需要根据员工 ID 获取详细信息。我在 API 中得到了预期的响应,但在那之后,在订阅方法中我无法将它分配给变量 EmployeeOrigData。有什么问题?

【问题讨论】:

  • .map(res => res.employeeData) 而不是 .map(res => res.json().employeeData)HttpClient 默认会为你解析 json。
  • @Igor 如果我尝试此操作,则会收到错误消息,即“响应”类型上不存在属性“employeeData”。
  • 您使用的是HttpClientModule还是过时的HttpModule
  • @Igor HttpModule :_(
  • 您应该升级到 HttpClientModule 或添加它,然后在您重构或添加新代码的任何地方开始使用它。

标签: c# angular typescript


【解决方案1】:

此答案适用于HttpClientModule

  • 在您的服务中使用.map(res => res.employeeData) 而不是.map(res => res.json().employeeData)HttpClient 默认会为你解析 json。
  • 使用Pipeable Operators 而不是“补丁操作员”。
  • 在您的方法中声明返回类型并利用类型安全性
import { Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

//....

GetEmployeeData(empID: string) : Observable<EmployeeData> {
    let params = new URLSearchParams();
    params.set('empID',empID);

    return this.http.get<{employeeData: EmployeeData}>(Url, { params: params })
      .pipe(map(res => res.employeeData)
        , catchError(this.handleError));
}
export interface EmployeeData {
  // members here
}

【讨论】:

    【解决方案2】:

    如下更改您的订阅

        this.service.GetEmployeeData(this.addEmployeeID)
                .subscribe((response) => 
                {
                    this.EmployeeOrigData = response;
                },
                (err) => 
                {
                    if (err == '404 - Not Found')
                      this.Message('info', err, 'Update Unsuccessful - Server error');
                    else
                      this.Message('error', 'Error', err);
                },
    () => {
    if(
            this.EmployeeOrigData.EmployeeID == this.newID
            && this.EmployeeOrigData.EmployeeName == this.newName
            && this.EmployeeOrigData.EmployeeContact == this.newContact
            && this.EmployeeOrigData.EmployeeStatus == this.newStatus
            && this.EmployeeOrigData.EmployeeAddress == this.newAdress
        )
        {
            this.Message('info', 'Update invalid');
        }};
    

    在 UpdateEmployee() 方法中调用 getEmployeeData() 方法。

    这将在订阅完成且数据一致时执行if条件。

    【讨论】:

      【解决方案3】:

      如果你的服务中的http是httpClient,那么你不需要使用res.json(),httpclient.get()会自动为你做这些

       GetEmployeeData(empID: string) {
            let params = new URLSearchParams();
            params.set('empID',empID)
            return this.http.get(Url, { params: params })
                .map(res => res.employeeData)
                .catch(this.handleError);
        }
      

      【讨论】:

      • “响应”类型上不存在属性“employeeData”,这就是我将代码更改为此得到的结果
      猜你喜欢
      • 2018-05-01
      • 1970-01-01
      • 2018-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-16
      • 2021-02-25
      • 2020-07-06
      相关资源
      最近更新 更多