byC*_*der 7 javascript typescript angular
我打算做这样的架构:
storebookin store- 我有一个服务调用,从服务中获取数据,我对结果进行订阅.就像在angular2 docs(http)中描述的那样.
我想在嵌套组件中使用这些数据:form(formBuilder),材料设计元素等.
哪种方式最好,这样做?我是angular2的新手.
商店:
book: IBook;
constructor(private bookService: BookService) { }
ngOnInit() {
this.bookService.getBook('1')
.subscribe((book) => {
this.book = book;
});
}
Run Code Online (Sandbox Code Playgroud)
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 || { };
}
...
Run Code Online (Sandbox Code Playgroud)
书:
@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?*/
});
Run Code Online (Sandbox Code Playgroud)
因为,如果我book在任何地方都使用async (不是formBuilder) - 一切正常,但是在父组件中加载数据之后,formBuilder需要更新值.我怎样才能做到这一点?
bookID将 传递给BookComponent并让BookComponent处理异步 http 进入 怎么样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;
});
}
}
Run Code Online (Sandbox Code Playgroud)
否则,您有一些选项,请参见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
}
}
}
Run Code Online (Sandbox Code Playgroud)
更多信息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;
});
}
}
Run Code Online (Sandbox Code Playgroud)