0

[編輯1:precising我的http請求]獲取類的函數返回在奧裏利亞視圖

我的目標是做一個異步調用將數字轉換成字符串,並將其顯示在瀏覽器的用戶。我正在使用aurelia-http-client撥打電話。 首先,我嘗試了一個值轉換器,然後我在這裏讀到你不能對這些轉換器進行異步處理。現在我正在嘗試使用類和函數,但它似乎也不工作。 以下是我把我的* .ts文件(即模型,調用web服務使用它的位置,然後鬆開基準電壓源,軌道的真實名稱):

interface ITrack { 
    position: number; 
    reference: number; 
    realPosition: number 
} 

class Track implements ITrack { 
    position: number; 
    reference: number; 
    realPosition: number; 

    public getTitle() { 
     console.log('Getting title'); 
     return `This track is the ${this.realPosition} of ${this.reference}.`; 

    let client = new HttpClient(); 
    var json_tmp; 
    var realTitle = 'tmp'; 

    client.get('http://localhost:8800/webservice/' + this.reference) 
     .then(data => { 
     console.log('### START DATA'); 
     console.log(data.response); 
     console.log('### END DATA'); 
     var json_tmp = JSON.parse(data.response); 
     realTitle = json_tmp.tracklist[this.realPosition].title; 
     console.log('### RESPONSE: ' + realTitle); 
     }) 
     .then(function(res) { 
     console.log('### we are sending: ' + realTitle); 
     return(reponse); 
     }); 

    } 
} 

,這裏是我放的觀點:

<span class="position">${track.realPosition}</span>/<span class="reference">${track.reference}</span> 
- <span class="content">${track.getTitle()}</span></p> 

的「realPosition」和「參考」顯示正確,通過「的getTitle()」不會被觸發,我沒有在控制檯...

難道我處理這個問題? 在此先感謝!

+0

只是一個幸運的猜測,而不是一個答案:試着改變'public getTitle(){'''public get Title(){'和與其他屬性一樣使用它:'$ {track.Title}' – jevgenig

+0

很確定你不能使用帶有字符串插值的函數。我沒有看到HTTP請求適合您的代碼? – Tom

+0

對不起,我剪了太多的線。我不想用不必要的線路來解決目前的問題。 – djcaesar9114

回答

0

在您的viewmodel中寫入一個激活方法,該方法需要承諾,然後調用activate()中的getTitle方法。然後頁面只會在加載標題後加載。

class Track implements ITrack { 
    position: number; 
    reference: number; 
    realPosition: number; 

    public activate(): Promise <void> { 
     return getTitle(); 
    } 

    public getTitle(): Promise <void> { 
     console.log('Getting title'); 
     //here you can call the aurelia http method like this 
     return httpClient.getTitle().then((data) { 
      this.position = data.position; 
      this.reference = data.reference; 

     }); 

    } 
} 
+0

Mmm激活可以是一個很好的解決方案。我試圖用我的http請求實現你的代碼,但我不認爲我明白了。我編輯了我的初始文章,更詳細地解釋了我提出的請求:在調用帶有這些數字作爲參數的webservice後,我獲取2個數字並獲取一個字符串。 – djcaesar9114

0

我不知道有什麼用這個return語句:

return `This track is the ${this.realPosition} of ${this.reference}.`; 

一切功能之後 '迴歸' 將不會被執行,其中包括:

let client = new HttpClient(); 

正如其他人已經指出的,最好的解決方案是在激活方法中調用異步http調用,完全按照Aurelia Skeleton示例中的建議https://github.com/aurelia/skeleton-navigation/blob/master/skeleton-typescript/src/users.ts

之後,你只需要從模板中讀取屬性而不需要調用任何方法