2016-03-02 82 views
0
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'); 
    } 
} 

請檢查上面的代碼片段。那麼, this.http.get(...)不會向網址發送請求,但$ .ajax(...)正在工作,有人可以幫忙嗎?http.get不能在angular js中工作2

我已經從使用服務組件類調用該方法,

import {Component, OnInit} from 'angular2/core'; 
import {Router} from 'angular2/router'; 
import {SampleInfoService} from 'app/booking-info/service/sample-info-service'; 
import {SampleInfoModel} from 'app/booking-info/model/sample-info-model'; 
import {TranslateService, TranslatePipe} from 'ng2-translate/ng2-translate'; 
import {HTTP_PROVIDERS} from 'angular2/http'; 


@Component({ 
    selector: 'sample-information', 
    templateUrl: 'app/sample-info/templates/sample-info.html', 
    providers: [SampleInfoService], 
    pipes: [TranslatePipe] 

}) 
export class SampleInfoComponent implements OnInit { 
    public sampleInformation = {}; 
    constructor(private _sampleInfoService: SampleInfoService,private _translate: TranslateService) { 
      this.initializeTranslateServiceConfig(_translate, 'en') 
     } 

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

回答

4

更新 我假設你嘗試已經收到值之前訪問this.sampleInformation

觀察結果是異步的,getInfo().subscribes()在執行SampleInfo => this.sampleInformation = SampleInfo之前返回。這僅在稍後來自服務器的響應到達時執行;

嘗試

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

觀測值都默認爲懶惰。你需要this.getinfo().subscribe(x => {})來發起請求。

+1

顯然,您的問題沒有提供足夠的信息。 –

+0

感謝您關注@günter-zöchbauer,我編輯了這個問題,請看一看。 – deepugn

+1

我更新了我的答案。如果您看到實際製作的請求,請檢查瀏覽器控制檯。 –