2016-03-16 69 views
3

這是我的代碼編譯時會拋出錯誤:打字稿錯誤:屬性「價值」並不在類型存在「可觀察<any>」

export class NoticeService { 
    public notice: Observable<any>; 
    private observer: any; 

    constructor(private translate: TranslateService) { 
    this.notice = new Observable(observer => { 
     this.observer = observer; 
    }).share(); 
    } 

    create(value: string) { 
    let translatedValue = this.translate.get(value).value; 
    this.observer.next(translatedValue); 
    } 
} 

console.log(this.translate.get(value))輸出爲:

ScalarObservable {_isScalar: true, value: "Some proper value!", etc. 

的輸出console.log(translatedValue)是:

"Some proper value!" 

錯誤是:

ERROR in [default] /somePath/notice.service.ts:21:52 
Property 'value' does not exist on type 'Observable<any>'. 

線路21:

let translatedValue = this.translate.get(value).value; 

出了什麼問題?


更新:

我使用NG2-翻譯,這是get方法:返回

/** 
* Gets the translated value of a key (or an array of keys) 
* @param key 
* @param interpolateParams 
* @returns {any} the translated key, or an object of translated keys 
*/ 
TranslateService.prototype.get = function (key, interpolateParams) { 
    var _this = this; 
    if (!key) { 
     throw new Error('Parameter "key" required'); 
    } 
    // check if we are loading a new translation to use 
    if (this.pending) { 
     return this.pending.map(function (res) { 
      return _this.getParsedResult(_this.parser.flattenObject(res), key, interpolateParams); 
     }); 
    } 
    else { 
     var translations = void 0; 
     if (this.translations[this.currentLang]) { 
      translations = this.parser.flattenObject(this.translations[this.currentLang]); 
     } 
     return Observable_1.Observable.of(this.getParsedResult(translations, key, interpolateParams)); 
    } 
}; 
+0

什麼是'TranslateService'的'GET'方法的內容?謝謝! –

+0

謝謝您的回覆,我更新了我的問題。 –

+1

謝謝!既然可觀察物被返回,你爲什麼不訂閱呢?就像這樣:'this.translate.get(value).subscribe(translatedValue => this.observer.next(translatedValue));' –

回答

7

由於可觀察到的,需要申請就可以了。事情是這樣的:

create(value: string) { 
    this.translate.get(value).subscribe(translatedValue => { 
    this.observer.next(translatedValue); 
    }); 
} 

,而不是嘗試直接從中獲得價值...

1

要誰也尋求一種更方便的方法的任何用戶:在此期間開發商NG2,添加翻譯直接加載該值的'instant()'方法(必須首先加載您的TranslationLoader才能正常工作):請參閱https://github.com/ocombe/ng2-translate/issues/20,或者,如果在使用translate.instant(key)之前,TranslationLoader未發生加載並且只有鑰匙可見,另一個問題通過等待onLangChange事件處理:https://github.com/ocombe/ng2-translate/issues/85

constructor (private translate : TranslateService){ 
    translate.onLangChange.subscribe((event: LangChangeEvent) => { 
     ... 
     let lesson = new Lesson(); 

     lesson.title = translate.instant("lesson_1_title"); 

     }); 
} 

不要忘記從加載LangChange在.TS控制器文件的標題NG2翻譯:

import {TranslatePipe,TranslateService, LangChangeEvent} from 'ng2-translate/ng2-translate'; 
相關問題