http get之后,Angular Typescript类中的方法为null [英] methods in angular typescript class are null after http get

查看:65
本文介绍了http get之后,Angular Typescript类中的方法为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular 2上编写了这样的类:

I'm on Angular 2 and coded a class like so:

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;
     }
)

但是我无法在组件的Books数组的任何成员中访问功能book.incRead(3).

But I can't access the function book.incRead(3) in any of the members of the Books array in the component.

也许HttpClient的Get方法无法正确实例化,否则我将不得不映射到另一个数组以访问该类中的public方法.

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.

我尝试了一些解决方法,但是代码不必要地弄脏了.

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.

编辑

我已经改变了班级,现在我可以这样:

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;
     }

}

并从服务器获取数据(使用这种方法: HttpClient未运行构造器)我可以使用对象分配

And to get data from the server (using this approach: HttpClient not running constructor) I can use Object assign

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函数将是完美的,但是我将在一个新问题中打开它.

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.

祝您编程愉快!

约瑟夫.

推荐答案

您必须实际制作书籍对象:

You have to actually make book objects:

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

您必须创建一个接受"any"对象的构造函数:

You have to create a constructor that takes an 'any' object:

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

这篇关于http get之后,Angular Typescript类中的方法为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆