无法从异步调用中检索数据

时间:2017-09-13 10:52:49

标签: javascript angular typescript asynchronous

我在我的角应用中使用ngx-translate服务进行翻译。我想创建一个接受需要返回的字符串路径的方法。我的方法如下:

public translateString(parameter: string): string {
    let message = "";
    this.translate.get(parameter).subscribe((response) => {
        message = response;
    });
    return message;
}

但它总是返回空字符串,我认为问题是订阅调用,所以返回消息在message = response之前执行。任何解决方案?

3 个答案:

答案 0 :(得分:0)

数据不是同步可用的。您需要返回observable,然后调用者可以订阅在消息可用后执行他们需要执行的操作。

Option Explicit

Sub VBAPivot()

Dim Sht1 As Worksheet
Dim NewSht As Worksheet
Dim PvtCache As PivotCache
Dim PvtTbl As PivotTable

Dim PvtRange As Range
Dim LastRow As Long

Set NewSht = ThisWorkbook.Sheets.Add ' add new sheet

Set Sht1 = ThisWorkbook.Worksheets("Sheet1")
With Sht1
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

    ' set the PivotCach DataSource Range
    Set PvtRange = .Range("A1:X" & LastRow)
End With

' Set the Pivot Cache
Set PvtCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, PvtRange.Address(False, False, xlA1, xlExternal))

' create a new Pivot Table in the new added sheet, in "A3"
Set PvtTbl = NewSht.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=NewSht.Range("A3"), TableName:="PivotTable1")

With PvtTbl ' modify Pivot-Table properties

    With .PivotFields("Bnlunit")
        .Orientation = xlPageField
        .Position = 1
    End With
    With .PivotFields("Period")
        .Orientation = xlColumnField
        .Position = 1
    End With

    ' add Field as Sum of
    .AddDataField .PivotFields("Amount"), "Sum of Amount", xlSum

    With .PivotFields("Hdaccount_agr_3(T)")
        .Orientation = xlRowField
        .Position = 1
    End With
End With

End Sub

答案 1 :(得分:0)

使用instant

不需要任何观察。

this.message =   this.translate.instant('Language')

答案 2 :(得分:-1)

你需要在subscribe中返回你的消息。就像这样:

public translateString(parameter: string): string {
    let message = "";
    this.translate.get(parameter).subscribe((response) => {
        message = response;
        return message;
    });
}