Angular 从服务到组件数组

Angular from service to component array

我正在努力使用 Angular 服务,但无法找出问题所在。

我正在开发一个图书应用程序(带有 Promises)。出于效率原因,我正在通过服务注入重构我的代码。我将服务用于所有 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;
    }
}

把你的两个函数改成这个:

 populateBookList(msgs){
       return this.http.get(this.urlRef+"book").map(response => {
            this.bookList = response.json() as Array<Book>;
            console.log(this.bookList);
            msgs.push({severity:'info', summary:'Book list',detail:'Loaded succesfully !'}
            return this.bookList;
       }).catch(() => msgs.push({severity:'error', summary:'Book list',detail:'Can not load list.'}));;
    }


    constructor(private httpService:HttpService, private http:Http){
        this._httpService = httpService;
        this._httpService.populateBookList(this.msgs).subscribe(res => {
            this.books = res;
        });
    }

你会得到你想要的结果。

另一个解决方案是从 Promises 切换到 map。

在我的例子中,我必须得到一个已知对象的 Json。 先说服务! 为此,我调用我的 RS 来检索类型为 Observable>:

的 JSON
getBooks():Observable<Book[]>{
        return this.http.get(this.urlRef+"book").map(this.extractData);
    }

extractData 方法处理响应(我将它本身用作方法,因为我稍后会重用它):

extractData(res: Response){
        return res.json()
    }

其次是我的组件。 我在我的装饰器中将服务添加到我的提供者:

@Component({
    selector:'lib-book',
    templateUrl:'./book.component.html',
    providers: [ HttpService ]
})

在构造函数中实例化它:

constructor(private httpService:HttpService){}

然后订阅(如 Vivek Doshi 所示,再次感谢!)我的服务方法,错误和成功处理:

ngOnInit(){ 
     this.httpService.getBooks()
      .subscribe(
          // opération à réaliser
          data => {this.books = data}, 
          // gestion de l'erreur
          ()=> this.msgs.push({severity:'error', summary:'Book list',detail:'Can not load list.'}), 
          // gestion de la réussite
          () => this.msgs.push({severity:'info', summary:'Book list',detail:'Loaded succesfully !'})) 
    }

供以后参考,订阅工作如下: componentORservice.method().subscribe(数据处理、错误处理、成功处理).

再次感谢!

完整代码如下:

服务:

import { Injectable } from "@angular/core";
import { Http, Response } from '@angular/http';

import { Observable } from "rxjs/Observable";

import { Author } from '../../domain/author';
import { Book } from '../../domain/book';

@Injectable()
export class HttpService{
private urlRef:String = "http://your_url";

    constructor(private http:Http){
    }

    getBooks():Observable<Book[]>{
        return this.http.get(this.urlRef+"book").map(this.extractData);
    }

    getAuthors():Observable<Author[]>{
        return this.http.get(this.urlRef+"author").map(this.extractData);
    }

    extractData(res: Response){
        return res.json()
    }
}

和组件:

import { Component, OnInit, Input } from '@angular/core';
import { Http } from '@angular/http';
import { Message } from 'primeng/primeng';

import { HttpService } from './service/http.service';
import { Observable } from 'rxjs/Observable';

import { Book } from '../domain/book';
import { Author } from '../domain/author';

@Component({
    selector:'lib-book',
    templateUrl:'./book.component.html',
    providers: [ HttpService ]
})

export class BookComponent implements OnInit{
        books:Array<Book>;
        msgs:Message[]=[];

  constructor(private httpService:HttpService){
    }

    ngOnInit(){ 
     this.httpService.getBooks()
      .subscribe(
          data => {this.books = data}, 
          ()=> this.msgs.push({severity:'error', summary:'Book list',detail:'Can not load list.'}), 
          () => this.msgs.push({severity:'info', summary:'Book list',detail:'Loaded succesfully !'})) 
    }
}