我打算做这样的架构:
storebook在 store - 我有一个服务调用,它从服务获取数据,我对结果进行订阅。就像在 angular2 文档 (http) 中描述的那样。
我想在嵌套组件中使用这些数据:表单 (formBuilder)、 Material 设计元素等。
哪种方式最好?我是 angular2 的新手。
商店:
book: IBook;
constructor(private bookService: BookService) { }
ngOnInit() {
this.bookService.getBook('1')
.subscribe((book) => {
this.book = book;
});
}
图书服务:
...
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?*/
});
因为,如果我在任何地方都使用异步 book(不是 formBuilder)- 一切正常,但是 formBuilder 需要在父组件中加载数据后更新值。我该怎么做?
最佳答案
如何将 bookID 传递给 BookComponent 并让 BookComponent 在 ngInit 中处理异步 http 获取?
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
parent 和 child 通过服务进行交流
@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 : get data from http in parent-component and subscribe on it nested,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41493955/