从服务到组件数组的角度

时间:2017-04-09 15:59:13

标签: angular service angular-promise

我正在与Angular Services斗争,但无法找出问题所在。

我正在开发一个书籍应用程序(使用Promises)。出于效率原因,我正在使用服务注入重构我的代码。我对所有的http请求使用该服务(后面有一个休息服务),在服务中正确检索数据但是没有办法在组件中获取它。 要检查它是否正确完成,我在服务承诺中添加了一个console.log(populateBookList())。 控制台显示正确的列表。

我还在我的组件中添加了一个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;
    }
}

2 个答案:

答案 0 :(得分:0)

将两个功能更改为:

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

您将获得预期的结果。

答案 1 :(得分:0)

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

在我的情况下,我必须为一个已知对象获得一个Json。 首先是服务! 为此,我调用我的RS来检索一个类型为Observable&gt;:

的JSON
gmondesi@MRT-3-011 MINGW64 ~/Documents/GitHub/docker-django-tutorial (master)
$ docker-compose up
Starting dockerdjangotutorial_db_1
Starting dockerdjangotutorial_web_1
Attaching to dockerdjangotutorial_db_1, dockerdjangotutorial_web_1
db_1   | LOG:  database system was interrupted; last known up at 2017-04-09 22:0
0:10 UTC
db_1   | LOG:  database system was not properly shut down; automatic recovery in
 progress
db_1   | LOG:  invalid record length at 0/150F2C0: wanted 24, got 0
db_1   | LOG:  redo is not required
db_1   | LOG:  MultiXact member wraparound protections are now enabled
db_1   | LOG:  database system is ready to accept connections
web_1  | Performing system checks...
web_1  |
web_1  | System check identified no issues (0 silenced).
web_1  |
web_1  | You have 13 unapplied migration(s). Your project may not work properly
until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
web_1  | Run 'python manage.py migrate' to apply them.
web_1  | April 09, 2017 - 23:58:45
web_1  | Django version 1.11, using settings 'composeexample.settings'
web_1  | Starting development server at http://0.0.0.0:8000/
web_1  | Quit the server with CONTROL-C.
web_1  | Invalid HTTP_HOST header: '192.168.99.100:8000'. You may need to add u'
192.168.99.100' to ALLOWED_HOSTS.
web_1  | [10/Apr/2017 00:00:03] "GET / HTTP/1.1" 400 57374
web_1  | Invalid HTTP_HOST header: '192.168.99.100:8000'. You may need to add u'
192.168.99.100' to ALLOWED_HOSTS.
web_1  | [10/Apr/2017 00:00:24] "GET / HTTP/1.1" 400 57486
web_1  | Invalid HTTP_HOST header: '192.168.99.100:8000'. You may need to add u'
192.168.99.100' to ALLOWED_HOSTS.
web_1  | [10/Apr/2017 00:00:25] "GET /favicon.ico HTTP/1.1" 400 57409
web_1  | Invalid HTTP_HOST header: '192.168.99.100:8000'. You may need to add u'
192.168.99.100' to ALLOWED_HOSTS.
web_1  | [10/Apr/2017 00:01:51] "GET / HTTP/1.1" 400 57486
web_1  | Invalid HTTP_HOST header: '192.168.99.100:8000'. You may need to add u'
192.168.99.100' to ALLOWED_HOSTS.
web_1  | [10/Apr/2017 00:01:51] "GET /favicon.ico HTTP/1.1" 400 57670
web_1  | Invalid HTTP_HOST header: '192.168.99.100:8000'. You may need to add u'
192.168.99.100' to ALLOWED_HOSTS.
web_1  | [10/Apr/2017 00:02:29] "GET / HTTP/1.1" 400 57159
web_1  | Invalid HTTP_HOST header: '192.168.99.100:8000'. You may need to add u'
192.168.99.100' to ALLOWED_HOSTS.
web_1  | [10/Apr/2017 00:02:30] "GET /favicon.ico HTTP/1.1" 400 57280
web_1  | Invalid HTTP_HOST header: '192.168.99.100:8000'. You may need to add u'
192.168.99.100' to ALLOWED_HOSTS.
web_1  | [10/Apr/2017 00:02:30] "GET /favicon.ico HTTP/1.1" 400 57280
web_1  | Invalid HTTP_HOST header: '192.168.99.100:8000'. You may need to add u'
192.168.99.100' to ALLOWED_HOSTS.
web_1  | [10/Apr/2017 00:02:37] "GET / HTTP/1.1" 400 57374
web_1  | Performing system checks...
web_1  |
web_1  | System check identified no issues (0 silenced).
web_1  |
web_1  | You have 13 unapplied migration(s). Your project may not work properly
until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
web_1  | Run 'python manage.py migrate' to apply them.
web_1  | April 10, 2017 - 00:03:08
web_1  | Django version 1.11, using settings 'composeexample.settings'
web_1  | Starting development server at http://0.0.0.0:8000/
web_1  | Quit the server with CONTROL-C.
web_1  | Invalid HTTP_HOST header: '192.168.99.100:8000'. You may need to add u'
192.168.99.100' to ALLOWED_HOSTS.
web_1  | [10/Apr/2017 00:03:10] "GET / HTTP/1.1" 400 57292
web_1  | Performing system checks...
web_1  |
web_1  | System check identified no issues (0 silenced).
web_1  |
web_1  | You have 13 unapplied migration(s). Your project may not work properly
until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
web_1  | Run 'python manage.py migrate' to apply them.
web_1  | April 10, 2017 - 00:03:17
web_1  | Django version 1.11, using settings 'composeexample.settings'
web_1  | Starting development server at http://0.0.0.0:8000/
web_1  | Quit the server with CONTROL-C.
Gracefully stopping... (press Ctrl+C again to force)
Stopping dockerdjangotutorial_web_1 ... done
Stopping dockerdjangotutorial_db_1 ... done

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

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

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

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

在构造函数中实例化它:

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

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

constructor(private httpService:HttpService){}

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

再次感谢!

这是完整的代码:

服务:

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 !'})) 
    }

组件:

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