[英]methods in angular typescript class are null after http get
I'm on Angular 2 and coded a class like so: 我在Angular 2上编写了如下代码:
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;
}
}
Then to get data from the server at a component: 然后从组件的服务器获取数据:
this._httpClient.Get<Book[]>(url).subscribe(
(books: Book[]) => {
this.books = books;
}
)
But I can't access the function book.incRead(3) in any of the members of the Books array in the component. 但是我无法在组件的Books数组的任何成员中访问功能book.incRead(3)。
Maybe HttpClient Get method does not instantiate correctly or I'll have to map to another array to get access to the public method in the class. 也许HttpClient的Get方法无法正确实例化,否则我将不得不映射到另一个数组以访问类中的public方法。
I've tried some workaround but code gets unnecessarily dirt. 我尝试了一些解决方法,但是代码不必要地弄脏了。
Please be kind. 请客气。 I have really done my homework and been unable to find a question about as clear as this. 我确实完成了功课,却找不到如此清晰的问题。
EDIT 编辑
I've changed the class a bit and now I can go this way: 我已经改变了班级,现在我可以这样:
export class Book{
title: string;
author: string;
read: integer;
author: string;
constructor() {
}
public incRead(times: integer){
this.read = this.read + times;
}
}
And to get data from the server (using this approach: HttpClient not running constructor ) I can use Object assign 并从服务器获取数据(使用这种方法: HttpClient未运行构造函数 ),我可以使用对象分配
this._httpClient.Get<Book[]>(url).subscribe(
(books: Book[]) => {
const tempbooks = new Array<Book>();
books.forEach(book => {
tempbooks.push(Object.assign(new Book(),book);
}
}
)
Now it would be perfect adding a post function in the class using the Http service, but I'll open it in a new question. 现在使用Http服务在类中添加post函数将是完美的,但是我将在一个新问题中打开它。
Happy coding! 编码愉快!
Josep. 何塞普。
You have to actually make book objects: 您必须实际制作书籍对象:
this._httpClient.Get<Book[]>(url).subscribe(
(books: Book[]) => {
this.books = books.map((b) => new Book(b));
}
)
You have to create a constructor that takes an 'any' object: 您必须创建一个接受“ any”对象的构造函数:
constructor(book?: any) {
if (book != null) {
this.title = book.title;
this.author = book.author;
this.read = book.read;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.