2017-01-05 2 views
7

중첩에 나는 그런 건축 할 계획 구독 :각도 2 : 부모 요소에 HTTP 데이터를 얻을하고

  • 구성 요소를 store
  • - 중첩 된 구성 요소 book

에서 store - 나는 서비스로부터 데이터를 얻는 서비스 호출을 가지고 있으며 결과에 대한 구독을한다. 그것은 angular2 문서 (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?*/ 
}); 

이 있기 때문에 내가 사용하는 경우 비동기 book 어디서나 (formBuilder가 아님) - 모두 정상이지만 formBuilder는 부모 구성 요소에 데이터를로드 한 후에 값을 업데이트해야합니다. 내가 어떻게 할 수 있니?

답변

1

무엇 bookIDBookComponent에 전달하고 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; 
     }); 
    } 
} 

그렇지 않으면 당신은 내가 잠시 당신이 사용할 수 있다고 생각 두 가지 방법을 선택합니다 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; 
     }); 
    } 
} 
+0

를 통해 통신 저장? http 호출로주세요 ... – byCoder

+0

예를 들어 http : get을 두 번 호출하지 않으려 고합니다 (상점 및 책에서) - get-method를 한 번 호출하고이 데이터를 어디서나 사용하고 싶습니다. – byCoder

+0

btw , 양식을 업데이트하는 것이 좋습니다 : 'ngOnChanges (변경 : {[propKey : string] : SimpleChange}) {for (변경 사항의 propName을 허용) {if (propName === 'book'&& this.bookForm (control.setValue (this.book [k]);}})) {Object.keys (this.book) .forEach (k => {let control = this.bookForm.get (k); }}}' ? 또는 다른 값이있는 동적 양식을 채우기 위해 뭔가가 필요합니까? – byCoder

관련 문제