Невозможно получить ответ, используя подписку в Angular - PullRequest
0 голосов
/ 26 сентября 2019

Я пытаюсь получить ответ и назначить его переменной в методе подписки, а затем использовать эту переменную для извлечения и использования извлеченных данных.Ниже мой код:

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);
}

Здесь мне нужно получитьдетали на основе идентификатора сотрудника.Я получаю ожидаемый ответ в API, но после этого, внутри метода подписки, я не могу назначить его переменной EmployeeOrigData.Что может быть не так?

Ответы [ 3 ]

1 голос
/ 26 сентября 2019
  • В вашем сервисе используйте .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
}
0 голосов
/ 27 сентября 2019

Внесите изменения в подписку следующим образом

    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, когда подписка завершится иданные согласованы.

0 голосов
/ 26 сентября 2019

Если http в вашем сервисе является httpClient, вам не нужно использовать res.json (), httpclient.get () автоматически сделает это за вас

 GetEmployeeData(empID: string) {
    debugger;
      let params = new URLSearchParams();
      params.set('empID',empID)
  debugger;
      return this.http.get(Url, { params: params })
          .map(res => res.employeeData)
          .catch(this.handleError);
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...