Angular Typescript getter 和 setter 返回未定义

2024-01-10

我有一个类,我需要该类中的属性来返回对象中的一些字段。 我在 .Net 中这样做过几次,但在 Angular 中,我正在与返回的“未定义”作斗争。

我可以确认属性(transLanguageId、transLangDesc、翻译)已填充到 IBatchFile 上,但未返回到 GET 上。 GETTER 中甚至没有出现 console.log。我认为没有击中 GETTER 代码。

我在这里缺少什么?

预先感谢您的帮助。

model.ts

export class translationItem {  
  id: number;
  language: string;
  translation: string; 
}

export class IBatchFile {
  constructor(_transData: translationItem) {
    this._transData = new translationItem();
  }
  private _transData: translationItem;

  get transData(): translationItem {      
    this._transData.id = this.transLanguageId;
    this._transData.language = this.transLangDesc;
    this._transData.translation = this.translation;     
    return this._transData;
  };
  set transData(value: translationItem) {
     this._transData.id = value.id;
     this._transData.language = value.language;
     this._transData.translation = value.translation;
  };
  transLanguageId: number;
  transLangDesc: string;
  translation: string;
}

批处理文档列表.ts

private _batchFileListResults$ = new BehaviorSubject<IBatchFile[]>([]);

public loadDocList(batchid) {
  this.urlservice.getBatchFiles(batchid)         
  .subscribe(result => {      
    this._batchFileListResults$.next(result); //**result is of class IBatchFile**        

    this._batchFileListResults$.value.forEach(item => {          
      console.log(item.transData);  //**returns Undefined**
    });
}

url.service.ts

getBatchFiles(batchId: number) {             
        return this.dataservice.getBatchFiles(config.resources.Api.gatewayUri + config.resources.Api.getBatchFiles+"/"+batchId);
     }

数据服务.ts

getBatchFiles(url:string): Observable<IBatchFile[]> {        
        return this.http.get<IBatchFile[]>(url)
        .pipe(map(response => response))
        .pipe(catchError(this.handleError));
    }

假如说:

  • 您正在使用 HttpClient (@angular/common/http):
  • 你有class X

你需要知道它才能知道http.get<X>不返回实例X class.

字段已正确填充,但原型链未正确填充。 您可以自己测试一下(在浏览器 DevTools 中):

result.constructor  //ƒ Object()

将其与以下内容进行比较:

const x = new X();
x.constructor       //class X

因此,结果对象中缺少放置在对象原型上的任何项目(如方法和 get/set 访问器)。

在我的项目中,我将 HttpClient.get 的返回类型限制为类型 (type X代替class X)。当类型被编译掉时,您将避免这种奇怪的情况。

或者,您可以转换 HttpClient.get 的输出并通过构造函数实例化真实的类。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular Typescript getter 和 setter 返回未定义 的相关文章

随机推荐