方法在角打字稿类为空之后HTTP GET
我对角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。
你必须真正让书的对象:
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;
}
}
我编辑了代码来添加构造函数,并使其更接近真实行为 - 属性被初始化。 现在新书(b)显示了有关构造函数参数的错误。 –
我编辑了我的答案 – Carsten
对不起,我不能马上回答。我需要测试它,而真正的类有很多属性和方法。让我试试! –
什么是预期的行为? – Aravind
我试图在由HttpClient获取函数生成的每个对象上使用incRead方法。当httpClient获取数据(书籍数组,只有属性)时,该方法不可用。 –