2017-08-17 84 views
0

我是TS和角4的新手。我需要能夠顯示角度材料2 MdSnackBar內翻譯CLOSE字的用戶。我明白,你可以從這樣的代碼中調用NGX-翻譯翻譯服務:ngx翻譯與角材料2 MdSnackBar

this.translate.get('ERROR.CLOSE').subscribe((res: string) => { 
    console.log(res); 
}); 

的事情是,我需要能夠顯示這個角度材料2元中調用MdSnackBar

我想是這樣執行它:

this.snackBar.open(error, this.getCloseWord(), { 
    duration: 10000, 
}) 

private getCloseWord() { 
    this.translate.get('ERROR.CLOSE').subscribe((res: string) => { 
     console.log(res); 
    }); 
    } 

但我不知道如何使getCloseWord()方法返回一個正確的字串值,可觀察到的。

回答

1

嘗試如下:

public someMethod() { 
    const error = ...some error...; 
    ... 
    this.translate.get('ERROR.CLOSE').subscribe((res: string) => { 
    this.snackBar.open(error, res, { duration: 10000 }); 
    }); 
    ... 
} 

的「獲得()」函數返回一個可觀察所以只要打開你的小吃吧當‘GET’訂閱。然後你知道你的翻譯是可用的。


與一個以上的觀察者A的解決辦法如下:

public someMethod() { 
    const newObserver = new ReplaySubject(); 
    let error = null; 
    let close = null; 

    this.translate.get('ERROR.MESSAGE').subscribe((translation: string) => { 
     error = translation; 
     newObserver.next(); 
    }); 

    this.translate.get('ERROR.CLOSE').subscribe((translation: string) => { 
     close = translation; 
     newObserver.next(); 
    }); 

    newObserver.subscribe(() => { 
     if(error && close) { 
      this.snackBar.open(error, close, { duration: 10000 }); 
     } 
    }); 
} 

還是最好的解決辦法就是將它們合併:

import "rxjs/add/observable/forkJoin"; 
... 
public someMethod(){ 
    const firstTranslationObs = this.translate.get('ERROR.MESSAGE'); 
    const secondTranslationObs = this.translate.get('ERROR.CLOSE'); 

    Observable.forkJoin([firstTranslationObs, secondTranslationObs]) 
     .subscribe(results => { 
     let error= results[0]; 
     let close = results[1]; 
     this.snackBar.open(error, close, { duration: 10000 }); 
     }); 
} 
+0

謝謝!這就像一個魅力!如果我想同時翻譯兩個元素,該怎麼辦?如何調整請求以請求兩個參數? –

+0

我編輯了我的答案。希望這是你的問題。 –