我對角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。
什麼是預期的行爲? – Aravind
我試圖在由HttpClient獲取函數生成的每個對象上使用incRead方法。當httpClient獲取數據(書籍數組,只有屬性)時,該方法不可用。 –