Angular 2:从父组件中的http获取数据并在其上嵌套订阅

时间:2017-01-05 20:19:43

标签: javascript angular typescript

我打算做这样的架构:

  • 组件store
  • - 嵌套组件book

store中 - 我有一个服务调用,从服务中获取数据,我对结果进行订阅。就像在angular2 docs(http)中描述的那样。

我想在嵌套组件中使用这些数据:表单(formBuilder),材料设计元素等。

哪种方式最好,这样做?我是angular2的新手。

商品

book: IBook;

constructor(private bookService: BookService) { }

ngOnInit() {
    this.bookService.getBook('1')
        .subscribe((book) => {
            this.book = book;
        });
}

bookService的:

...

getBook (id): Observable<IBook> {
    return this.http.get(this.url + '/' + id)
        .map(this.extractData)
        .catch(this.handleError);
}

private extractData(res: Response) {
    let body = res.json();
    return body || { };
}

...

图书:

@Input() book:IBook;

constructor() {}

ngOnInit() {
    /*How here can i subscribe on book http data get?, so that i can use async value in forms etc?*/
});

因为,如果我在任何地方使用async book(而不是formBuilder) - 一切正常,但是在父组件中加载数据之后,formBuilder需要更新值。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

如何将BookComponent传递给ngInit并让export class Book implements OnInit { @Input() bookID: number; private book: IBook; constructor(private bookService: BookService) {} ngOnInit() { this.bookService.getBook(this.bookID) .subscribe((book) => { this.book = book; }); } } 处理异步http进入export class Book implements OnChanges { @Input() book: IBook; ngOnChanges(changes: {[propKey: string]: SimpleChange}) { for (let propName in changes) { // handle updates to book } } }

@Injectable()
export class BookService {
  books = new Subject<IBook>();

  getBook(id): Observable<IBook> {
    return this.http.get(this.url + '/' + id)
    .map(d => {
      let book = this.extractData(d);
      this.books.next(book);
      return book;
    })
    .catch(this.handleError);
  }
  ...
}

@Component({
  selector: 'book',
  providers: []
})
export class Book implements OnDestroy {
  book: IBook
  subscription: Subscription;

  constructor(private bookService: BookService) {
    this.subscription = bookService.books.subscribe(
      book => {
        this.book = book;
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

@Component({
  selector: 'store',
  providers: [BookService]
})
export class Store {
  book: IBook;

  constructor(private bookService: BookService) { }

  ngOnInit() {
    this.bookService.getBook('1')
        .subscribe((book) => {
            this.book = book;
        });
  }
}

否则您有一些选项可在Launch Stack

中解释

我将简要介绍两种我认为可以使用的方法。

使用ngOnChanges拦截输入属性

2017-01-05 15:06:18 (5.50 MB/s) - Read error at byte 10357143/35563520 (Connection reset by peer). Retrying.

更多信息https://angular.io/docs/ts/latest/cookbook/component-communication.html

家长和孩子通过服务沟通

[Thu Jan 05 15:21:18.588286 2017] [:error] [pid 24756] [remote 10.11.30.20:52525] mod_wsgi (pid=24756): Exception occurred processing WSGI script '/var/www/xyz/wsgi.py'.
[Thu Jan 05 15:21:18.588407 2017] [:error] [pid 24756] [remote 10.11.30.20:52525] IOError: failed to write data