我正在與角服務苦苦掙扎,無法找出問題所在。從角度服務到組件陣列
我正在開發一本書應用程序(與承諾)。出於效率原因,我使用服務注入來重構我的代碼。我對所有的http請求使用該服務(後面有一個休息服務),數據可以在服務中正確檢索,但無法在組件中獲取。 要檢查它是否正確完成,我已在服務承諾(populateBookList())中添加了console.log。 控制檯顯示正確的列表。
我還在我的組件中添加了一個console.log來查看列表,它是空的。此外,組件書籍列表在服務之前加載。 我知道有什麼可疑的,但不知道哪裏> _ <
任何線索,建議,[其他]將非常感激!感謝你們!
這是我的組件:
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(){
}
}
這是我的服務
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;
}
}
你是做一個異步操作,但要同步做作業。含義:當您調用'getBooks'時,來自'populateBookList'的數據還沒有到達。 'populateBookList'中的'http.get'將會在2秒內得到列表,但是在請求'populateBookList'後立即請求'getBooks'中的書。 – echonax