这是我编译时抛出错误的代码:
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-translate,这是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 :(得分:8)
由于返回了一个observable,您需要订阅它。像这样:
create(value: string) {
this.translate.get(value).subscribe(translatedValue => {
this.observer.next(translatedValue);
});
}
而不是试图直接从中获取价值......
答案 1 :(得分:1)
对于同时搜索更方便方法的用户:同时ng2-translate的开发人员添加了'instant()'方法直接加载值(必须首先加载TranslationLoader才能使其工作) :请参阅https://github.com/ocombe/ng2-translate/issues/20或者,如果在使用translate.instant(key)之前没有加载TranslationLoader并且只有键可见,则通过等待onLangChange事件处理另一个问题:{{3 }}
constructor (private translate : TranslateService){
translate.onLangChange.subscribe((event: LangChangeEvent) => {
...
let lesson = new Lesson();
lesson.title = translate.instant("lesson_1_title");
});
}
不要忘记在.ts控制器文件的标题中从ng2-translate加载LangChange:
import {TranslatePipe,TranslateService, LangChangeEvent} from 'ng2-translate/ng2-translate';