http.get无法在角度js 2中工作

时间:2016-03-02 13:50:51

标签: angular

FederatedAuthentication.SessionAuthenticationModule.SignOut();
issuer = FederatedAuthentication.WSFederationAuthenticationModule.Issuer;
reply = FederatedAuthentication.WSFederationAuthenticationModule.Realm;
signOutRequestMessage = new SignOutRequestMessage(new Uri(issuer), reply);

请检查上面的代码段。在那里面, this.http.get(...)没有将请求发送到网址,但$ .ajax(...)正在运行,有人可以帮忙吗?

我已经从使用该服务的组件类中调用它,

import {Injectable} from 'angular2/core';
import {SampleInfo} from 'app/sample-info/model/sample-info-model';
import {HTTP_PROVIDERS, Http, Response, Headers, RequestOptions} from 'angular2/http';

import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';


@Injectable()
export class SampleService {
  constructor (private http: Http) {}

  private _url = 'http://localhost:9090/sample/details/1213';

  getInfo () {
    headers = new Headers({ 'Authorization': 'Basic AVBDIEtr009=' });
    options = new RequestOptions({ headers: headers });
    // $.ajax(this._url); 
    return this.http.get(this._url, options)
                    .map(res => <SampleInfo> res.json())
                    .do(data => console.log(data))
                    .catch(this.handleError);
  }

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

1 个答案:

答案 0 :(得分:4)

<强>更新 我假设您在收到值之前尝试访问this.sampleInformation

getInfo().subscribes()执行之前,Observable是异步和SampleInfo => this.sampleInformation = SampleInfo返回。这只有在服务器响应到来时才会执行;

尝试

getSampleInfo() {
    this._sampleInfoService.getInfo()
                 .subscribe(
                   SampleInfo => {
                     this.sampleInformation = SampleInfo;
                     console.log(this.sampleInformation);
                   },
                   error =>  this.errorMessage = <any>error);
}

<强>原始

默认情况下,Observable是懒惰的。您需要this.getinfo().subscribe(x => {})才能发起请求。