【问题标题】:Angular 2 - simple HTTP GET from component not workingAngular 2 - 来自组件的简单 HTTP GET 不起作用
【发布时间】:2016-07-12 11:29:45
【问题描述】:

我有一个 Angular 2 应用程序,它有一个简单的组件(见下文)。 它对 Web Api 端点进行简单的 GET 调用。 我可以使用邮递员调用端点,但是当这个组件尝试它失败时。永远不会进行调用,也不会输出任何错误。 我做错了什么?我以前也遵循过这种模式。

import { Component, Input }  from '@angular/core';
import { ROUTER_DIRECTIVES, Router } from '@angular/router';
import { Http,Response, Headers, RequestOptions  } from '@angular/http';
import { DomSanitizationService } from '@angular/platform-browser';
import { Observable } from 'rxjs/Observable';
import { ITile } from '../interfaces/tile';

@Component({
    selector: 'tile',
    template: require('../tile/tile.component.html'),
    styles: [require('../tile/tile.component.css').toString()],

    directives: [ROUTER_DIRECTIVES]
})

export class TileComponent {
    @Input() tile: ITile;

    constructor(private _http: Http) { }

    onSelect(id: string) {
        this.getProfileImage(id);
    }

    getProfileImage(id: string): Observable<string> {

     let url = 'http://localhost:2116/api/profileimage/5/';
     let headers = new Headers({ 'Accept': 'application/json' });
     let options = new RequestOptions({ headers: headers });

    return this._http.get(url, options)
            .map((response: Response) => <string>response.json())
            .catch(this.handleError);

    }

      private handleError(error: Response) {
        console.log(error);
        return Observable.throw(error.json().error || 'Server error');
    }

}

终点是这样的……

[AllowAnonymous]
[Route("api/profileimage/{userId}")]
public HttpResponseMessage Get(string userId)
{ 
    return Request.CreateResponse(HttpStatusCode.OK, "success");
}

【问题讨论】:

  • 你的角度版本是多少?
  • "@angular/core": "2.0.0-rc.3"
  • 它是怎么失败的?正在显示哪些消息?
  • 就是这个问题,没有错误输出,也没有到达终点。

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


【解决方案1】:

您需要订阅 get 方法(一个冷的 observable)来触发调用。

【讨论】:

    猜你喜欢
    • 2011-03-15
    • 2020-07-11
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 2016-04-03
    相关资源
    最近更新 更多