【问题标题】:Angular 2 get data from ID using web apiAngular 2 使用 web api 从 ID 获取数据
【发布时间】:2017-08-16 07:33:23
【问题描述】:

我有从 EmpID 获取数据的 Web API 方法,我从 Angular 2 调用此方法并希望将数据绑定到表单以更新它。

我认为我没有从服务中正确调用 Web API 方法, 但它给出了我们找不到这个 Web API 方法的错误。

Web API 方法:

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

以下是我的服务:

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

下面是我的组件类:

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

【问题讨论】:

  • 如果您收到跨源请求错误,请检查浏览器中的网络选项卡
  • @Malwaregeek ,是的,我遇到了跨源网络错误。

标签: angular asp.net-web-api asp.net-web-api2


【解决方案1】:

您的代码看起来不错,但我认为您忘记将 api 放在您的 url 中,这就是您没有获得所需信息的原因。

您也可以考虑为基本 url 创建一个变量,然后将 id 添加到它的末尾,这样您的代码会变得更简洁。

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

这是您的 http 调用的固定版本,在 url 中添加了 api 关键字。

P.S:您还可以考虑将响应转换为确切的对象(如果您为此目的创建了特定的类)

类似这样的:

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

正如我所说,这是考虑到您已经创建了一个 Employee 类这一事实。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    • 1970-01-01
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多