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

我打算做这样的架构:

>组件商店
> – 嵌套组件书

在商店 – 我有一个服务电话,从服务中获取数据,我对结果进行订阅.就像在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?*/
});

因为,如果我到处使用异步书(不是formBuilder) – 一切正常,但是在父组件中加载数据之后,formBuilder需要更新值.我怎样才能做到这一点?

最佳答案
将bookID传递给BookComponent并让BookComponent处理ngInit中的异步http get怎么样?

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

否则,您有一些选项可在https://angular.io/docs/ts/latest/cookbook/component-communication.html中解释

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

拦截输入属性随ngOnChanges而变化

export class Book implements OnChanges {
  @Input() book: IBook;
  ngOnChanges(changes: {[propKey: string]: SimpleChange}) {
    for (let propName in changes) {
       // handle updates to book
    }
  }
}

更多信息https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

家长和孩子通过服务进行交流

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

转载注明原文:javascript – Angular 2:从父组件中的http获取数据并在其上嵌套订阅 - 代码日志