methods in angular typescript class are null after http get

时间:2017-12-18 07:05:13

标签: angular typescript

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

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

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.

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

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.

Happy coding!

Josep.

1 个答案:

答案 0 :(得分:1)

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:

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