2017-04-19 100 views
-1

好的,這裏應該是一些簡單的Typescript代碼。無論如何,在我看來......從Typescript承諾返回字符串值

public showDialog(theNickname: string): string {   
     var req = { 
      method: 'POST', 
      url: '/Q/GetUserDetails', 
      data: { nickname: theNickname } 
     } 
     this.$http(req).then((response) => { 

      var c = "Nickname: " + response.data.Nickname + "<br/>"; 
      c = c + "Score: " + response.data.Score + "<br/>"; 
      c = c + "Followers: " + response.data.Followers + "<br/>";    
      return c;    

     }); 

    } 

當然,它沒有返回字符串值,因爲它是作爲承諾返回。我不想使用超時功能。我怎樣才能返回字符串值?它在html上被一個Angular函數調用。如果我改變

public showDialog(theNickname: string): string { 

public showDialog(theNickname: string): any { 

它仍然無法正常工作。我在UI.Bootstrap Popover中使用此代碼。

謝謝!

回答

2

古答案是正確的,但你可能會更awesomer和使用異步/等待:

async function showDialog(theNickname: string): Promise<string> {   
     const req = { 
      method: 'POST', 
      url: '/Q/GetUserDetails', 
      data: { nickname: theNickname } 
     } 
     const response = await this.$http(req); 
     return `Nickname: ${response.data.Nickname 
      }<br/>Score: ${response.data.Score 
      }<br/>Followers: ${response.data.Followers}<br/>`; 
} 

async function caller() { 
    const message = await showDialog("TEST"); 
    alert(message); 
} 

檢查出來here

+0

你使用'async' /'await'生產的前端應用?編譯好的代碼(使用promises)似乎很複雜...... – Paleo

+1

它可能看起來很複雜@paleo,但它在數學上證明是可行的。我用它在prod沒有問題。 – Daryl