1

I have web API method to get data from EmpID and I call this method from Angular 2 and want to bind data to form to update that.

I think I do not call web API method correctly from service, but it gives error that we cannot find this web API method.

Web API method:

    [ Route("api/Employee/GetEdit/{id:int}") ]       
    public Employee GetEdit(int id) {
        return db.Employees.Where(t => t.EmpID == id).FirstOrDefault();
    }

Below is my service:

 GetEdit(id:any) {
    let headers = new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this.http.get('http://localhost:49221/Employee/GetEdit/' + id,  headers)
        .map((res: Response) => res.json());

    //return this.http.get('http://localhost:49221/api/Employee')
    //    .map(this.extractData)
    //    .catch(this.handleError);
}

Below is my component class:

 getEdit() {
    this._service.GetEdit(1).subscribe(              
        posts => this.employee = posts,
        error => console.error(error)
    )};
2
  • Check the network tab in your browser if you are getting a cross origin request error Commented Mar 23, 2017 at 19:30
  • @Malwaregeek , yes I got cross origin network error. Commented Mar 24, 2017 at 12:35

1 Answer 1

1

Your code looks just fine, but I think you have forgotten to put api in your url and that's why you are not getting the information you need.

You can also consider creating a variable for a base url and then just adding the id to the end of it, that way your code will become cleaner.

GetEdit(id:any) {
    let headers = new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this.http.get('http://localhost:49221/api/Employee/GetEdit/' + id,  headers)
        .map((res: Response) => res.json());

    //return this.http.get('http://localhost:49221/api/Employee')
    //    .map(this.extractData)
    //    .catch(this.handleError);
}

This is the fixed version of your http call with the api keyword added to the url.

P.S: You can also consider casting the response to the exact object(if you have a specific class created for the purpose)

Something like this:

getEdit() {
    this._service.GetEdit(1).subscribe(              
        posts => this.employee = <Employee>posts,
        error => console.error(error)
    )};

As I said this is considering the fact that you've created an Employee class.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.