我正在与角服务苦苦挣扎,无法找出问题所在。从角度服务到组件阵列
我正在开发一本书应用程序(与承诺)。出于效率原因,我使用服务注入来重构我的代码。我对所有的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