簡體   English   中英

Angular Typescript getter 和 setter 返回未定義

[英]Angular Typescript getter and setter returning Undefined

我有一個 class,我需要一個 class 中的屬性來返回 object 中的一些字段。 我已經在.Net 中這樣做了幾次,但是在 Angular 中,我正在與返回的“未定義”作斗爭。

我可以確認在 IBatchFile 上填充了屬性(transLanguageId、transLangDesc、翻譯),但沒有在 GET 上返回。 甚至沒有一個 console.log 出現在 GETTER 中。 沒有達到我認為的 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

因此,結果 object 中缺少放置在對象原型上的任何項目(如方法和 get/set 訪問器)。

在我的項目中,我將 HttpClient.get 的返回類型限制為類型( type X而不是class X )。 隨着類型被編譯掉,您將避免這種怪異。

或者,您可以從 HttpClient.get 轉換 output 並通過構造函數實例化真實類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM