0

I am trying to get response and assign that to a variable in the subscribe method and later use that variable to retrieve and use the data fetched. Below is my code:

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

Component:

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

Service:

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

Here I need to fetch the details based on the Employee ID. I am getting the expected response in the API but after that, inside the subscribe method I am not able to assign it to the variable EmployeeOrigData. What could be wrong?

5
  • .map(res => res.employeeData) instead of .map(res => res.json().employeeData). The HttpClient will parse the json for you by default. Commented Sep 26, 2019 at 15:52
  • @Igor if I try this, then I get the error that Property 'employeeData' does not exist on type 'Response'. Commented Sep 27, 2019 at 6:13
  • Are you using the HttpClientModule or the obsolete HttpModule? Commented Sep 27, 2019 at 10:15
  • @Igor HttpModule :_( Commented Sep 30, 2019 at 12:25
  • You should upgrade to HttpClientModule or add it and start using that anywhere you are refactoring or adding new code. Commented Sep 30, 2019 at 12:38

3 Answers 3

1

This answer is applicable to HttpClientModule.

  • In your service use .map(res => res.employeeData) instead of .map(res => res.json().employeeData). The HttpClient will parse the json for you by default.
  • Use the Pipeable Operators instead of the "patch operators".
  • Declare return types on your methods and make use of type safety
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
}
Sign up to request clarification or add additional context in comments.

Comments

0

Make changes to your subscription as follows

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

and inside UpdateEmployee() method just call getEmployeeData() method.

This will execute the if condition when the subscription is complete and data is consistent.

Comments

0

If the http in your service is a httpClient then you don't need to use res.json(), httpclient.get() automatically does that for you

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

1 Comment

Property 'employeeData' does not exist on type 'Response', this is what I get on changing the code to this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.