I'm struggling with Angular Services and can't find out what's the issue.
I'm working on a book app (with Promises). For efficiency reasons, I'm refactoring my code with service injection. I use the service for all the http requests (there's a rest service behind), the data are correctly retrieved in the service but there's no way to get it in the component. To check if it was done correctly i've added a console.log in the service promise ( populateBookList() ). The console shows the correct list.
I also added a console.log in my component to see the list, and it's empty. Moreover, the component book list is loaded before the service one. I know there's something fishy but can't figure out where >_<
Any clue, advice, [other] would be really appreciated! Thank you guys!
This is my component :
import { Component, OnInit, Input } from '@angular/core';
import { Http } from '@angular/http';
import { Book } from '../domain/book';
import { Message } from 'primeng/primeng';
import { Author } from '../domain/author';
import { HttpService } from './service/http.service';
import { Observable } from 'rxjs/Observable';
@Component({
selector:'lib-book',
templateUrl:'./book.component.html',
providers: [HttpService]
})
export class BookComponent implements OnInit{
_httpService: HttpService;
urlRef:String;
books:Array<Book>;
authorList:Array<Author>;
public msgs:Message[]=[];
constructor(private httpService:HttpService, private http:Http){
this._httpService = httpService;
this._httpService.populateBookList(this.msgs);
this.books = this._httpService.getBooks();
}
ngOnInit(){
}
}
This is my service
import { Injectable } from "@angular/core";
import { Book } from '../../domain/book';
import { Http } from '@angular/http';
import { Author } from '../../domain/author';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import { Observable } from "rxjs/Observable";
@Injectable()
export class HttpService{
private urlRef:String = "http://localhost:8080/Librarian-1.0/ws/";
private bookList:Array<Book>;
constructor(private http:Http){
this.bookList = new Array<Book>();
}
populateBookList(msgs){
this.http.get(this.urlRef+"book")
.toPromise()
.then(response => this.bookList = response.json() as Array<Book>)
.then(() => console.log(this.bookList))
.then(() => msgs.push({severity:'info', summary:'Book list',detail:'Loaded succesfully !'}))
.catch(() => msgs.push({severity:'error', summary:'Book list',detail:'Can not load list.'}));
}
getBooks():Book[]{
return this.bookList;
}
}