2017-12-18 103 views
0

我對角2和編碼的像這樣一類:方法在角打字稿類爲空之後HTTP GET

export class Book{ 
    title: string; 
    author: string; 
    read: integer; 
    private: _author; 

    constructor(author: string) { 
     this._author = author 
    } 

    public incRead(times: integer){ 
     this.read = this.read + times; 
    } 
} 

然後,在一個組件來獲得來自服務器的數據:

this._httpClient.Get<Book[]>(url).subscribe(
    (books: Book[]) => { 
     this.books = books; 
    } 
) 

但是我無法在組件的Books數組的任何成員中訪問函數book.incRead(3)。

也許HttpClient Get方法沒有正確實例化,或者我必須映射到另一個數組才能訪問類中的公共方法。

我試過一些解決方法,但代碼獲取不必要的污垢。

請善待。我真的做了功課,一直沒能找到一個清晰的問題。

編輯

我已經改變了類了一下,現在我可以走這條路:

export class Book{ 
    title: string; 
    author: string; 
    read: integer; 
    author: string; 

    constructor() { 
    } 

    public incRead(times: integer){ 
     this.read = this.read + times; 
    } 

} 

,並從服務器獲取數據(使用這種方法:HttpClient not running constructor)我可以使用對象分配

this._httpClient.Get<Book[]>(url).subscribe(
    (books: Book[]) => { 
     const tempbooks = new Array<Book>(); 
     books.forEach(book => { 
      tempbooks.push(Object.assign(new Book(),book); 
     } 
    } 
) 

現在,它將是完美的在使用Http服務的類中添加一個post函數,b我會在一個新的問題中打開它。

快樂編碼!

Josep。

+0

什麼是預期的行爲? – Aravind

+0

我試圖在由HttpClient獲取函數生成的每個對象上使用incRead方法。當httpClient獲取數據(書籍數組,只有屬性)時,該方法不可用。 –

回答

1

你必須真正讓書的對象:

this._httpClient.Get<Book[]>(url).subscribe(
    (books: Book[]) => { 
     this.books = books.map((b) => new Book(b)); 
    } 
) 

你必須創建一個構造函數的「任意」對象:

constructor(book?: any) { 
    if (book != null) { 
    this.title = book.title; 
    this.author = book.author; 
    this.read = book.read; 
    } 
} 
+0

我編輯了代碼來添加構造函數,並使其更接近真實行爲 - 屬性被初始化。 現在新書(b)顯示了有關構造函數參數的錯誤。 –

+0

我編輯了我的答案 – Carsten

+0

對不起,我不能馬上回答。我需要測試它,而真正的類有很多屬性和方法。讓我試試! –