2016-09-19 3 views
1

검색 양식과 결과 표시가있는 Angular 2 응용 프로그램을 같은 페이지에 구축하고 있습니다. 라우팅을 사용하여 결과 섹션을 표시했습니다. 따라서 부모 구성 요소는 여러 필드가있는 검색 양식이며 하위 구성 요소는 백엔드에서 결과를 얻고 표시합니다.부모로부터 자식으로 두 번 이상 데이터를 전달하는 방법

검색 기준에 여러 필드가 포함되어 있으므로 검색 기준을 공유 서비스를 통해 하위 구성 요소에 전달하고 있습니다.

부모 요소 :

@Component({ 
     templateUrl : 'app/search-form.template.html' 
    }) 
    export class SearchFormComponent { 

     constructor(private searchService : SearchService, 
       private router: Router){} 

     submitSearch(){ 
      this.searchService.setSearchCriteria(this.model); 
      this.router.navigate(['search-form/search-result']); 
     } 

하위 구성 요소 :

@Injectable() 
    export class SearchService{ 
     constructor (private http: Http) {} 

    setSearchCriteria(searchCriteria : SearchCriteria){ 
     this.searchCriteria = searchCriteria; 
    } 

    getSearchResult() : Observable<any> { 
     let body = JSON.stringify(this.searchCriteria); 
     let headers = new Headers({'content-type' : 'application/json'}); 
     let options = new RequestOptions({headers : headers}); 
     return this.http.post(this.baseUrl , body, options) 
      .map((res: Response) => res.json().root || {}); 
    } 

부모와 자식이 라우팅을 사용하여로드됩니다 여기

@Component({ 
     templateUrl: 'app/search-result/search-result.template.html' 
    }) 
    export class SearchResultComponent implements OnInit{ 
     private searchResult = [] ; 
     constructor(private searchService: SearchService) { } 

     ngOnInit() { 
       this.searchService.getSearchResult().subscribe(data => { 
       this.searchResult = data; 
      }); 

    } 

서비스 코드입니다. 여기에 라우팅 정보가 있습니다

const appRoutes : Routes = [ 
     { 
     path: '', 
     redirectTo: '/search-form', 
     pathMatch: 'full' 
    }, 
    { 
     path: 'search-form', component: SearchFormComponent, 
     children: [ 
      { path: ''}, 
      { path: 'search-result', component: SearchResultComponent } 
     ] 
     } 
     ]; 

main.html이 같은 모양입니다. 여기에 검색 양식 (부모) '검색 양식'


          
  
<nav class="navbar" > 
 
     <div class="container-fluid"> 
 
      <router-outlet></router-outlet> 
 
     </div> 
 
     </nav>

검색 form.template.html 부모의 submitSearch() 메소드가 부모로부터 제출 양식이라고


          
  

 

 
     <form #searchForm="ngForm" class="form-horizontal" (ngSubmit)="submitSearch()"> 
 
     <!-- form fields --> 
 
     <button type="submit" class="btn btn-sm btn-primary pull-right">Submit</button> 
 
    
 
     <div class="panel panel-primary"> 
 
      <!-- Search Result here --> 
 
      <router-outlet></router-outlet> 
 
     </div>

을 니펫을 렌더링 . 하위 구성 요소로 이동하여 searchResult를 표시합니다. 지금까지는 잘 작동합니다.

내가 원하는 것은 사용자가 화면에서 검색 기준을 변경하고 제출 버튼을 다시 눌러야한다는 것입니다. submitSearch() 메서드가 호출되었지만 하위 구성 요소의 결과가 업데이트되지 않습니다. 자식 구성 요소가 ngOnInit 메서드에서 서비스를 호출하기 때문에 루트가 원인이라고 생각합니다. 결과를 표시 한 후에 동일한 페이지에 있으므로 제출 단추를 다시 눌러도 하위 구성 요소가 다시 작성되지 않으므로 데이터가 새로 고쳐지지 않습니다.

상위 구성 요소에서 제출할 때 어떻게 새 searchResult를 사용하여 하위를 다시로드 할 수 있습니까?

+0

check this out이 쇼에 좀 더 세부 사항을 추가 할 수 있습니다, 검색 방법보다 약 Subject를 들어 약속

searchAndSetCurrent(criteria)L Promise<any> { return this.http.get(..).toPromise().then(result => { currentSearch.next(result); return this; }); } 

를 반환 할 수 있습니다 내비게이션 – mehta

답변

1

어떻게 유선 연결했는지 확실하지 않습니다. SearchResultComponentSearchFormComponent의 하위 항목이지만 setSearchCriteria을 실행 한 후 자체 구성 요소가있는 것처럼 탐색합니다. 템플릿을 볼 수 없기 때문에 무슨 일이 일어나는지 이해하기 어렵습니다.

일반적으로 이런 식으로 일하는 방법은 setSearchCriteria() 다음에 부모에게 getSearchResult()을 실행하고 그 결과를 @Input으로 전달하는 것입니다. ActivatedRoute 서비스와 같은 것을 사용하여 상위 항목을 탐색하는 경우 하위 코드를 ngOnInit에서 ngOnChanges으로 옮기면 입력이 변경되면 새로 고침됩니다.

+0

답장을 보내 주셔서 감사합니다. 질문에 대한 자세한 내용을 추가했습니다. 또한 자식의 @Input 필드를 사용하여 자식 구성 요소에 데이터를 전달하려고했습니다. 그러나 데이터 바인딩이 를 사용하여 수행되지 않으므로 부모가 자식에게 정보를 전달하는 방법을 확신하지 못합니다. 이것이 사소한 것이라면 내 무지를 유감스럽게 생각합니다. – mehta

+0

오케이, 코드를 약간 변경했습니다. 라우터를 사용하는 대신 결과에 따라 결과 섹션을 표시하거나 숨 깁니다. 검색 기준을 제출할 때 서비스를 호출하여 결과를 가져온 다음 @Input을 사용하여 하위 구성 요소로 전달합니다. 그 일은 지금 :) 당신의 도움에 감사드립니다. 답을 수락했습니다. – mehta

1

SearchService 안에 Subject이 있어야합니다. 그것을 currentResult과 같은 것으로 부르십시오. 피사체는 양방향으로 관찰 할 수있는 것처럼 생산자이자 소비자입니다. 그래서 부모 끝에서 당신은 생산자가 될 수 있고, 아이는 소비자를 끝낼 수 있습니다.

onInit에서 검색 조건을 설정하지 않으려는 경우가 있지만 상위에서 일부 동작이 발생하는 경우 일 수 있습니다.그렇다면 아이를위한 약간의 가치를 만들어 낼 수 있습니다.

어쩌면 'rxjs/주제에서이

수입 {주제} 같은;

@Injectable() 
class SearchService { 
    private currentSearch = new Subject<any>(); 

    searchAndSetCurrent(criteria) { 
    this.http.get(..).toPromise().then(result => { 
     currentSearch.next(result); 
    }); 
    } 

    getCurrentSearch(): Observable<any> { 
    // asObservable is not really necessary as you can subscribe 
    // to a subject. But to make sure people calling this method 
    // don't try to emit anything, we should just limit it 
    // to the capabilities of an Observable 
    return this.currentSearch.asObservable(); 
    } 
} 

이제 부모는 searchAndSetCurrent를 호출 할 수 있고, 아이가 가입 할 수 있습니다. 검색이 부모에 의해 호출 될 때마다, 결과가 들어올 때마다 자식이 그것을 얻습니다. 당신이 부모의 결과로 뭔가를하려는 경우

, 당신은 당신이

관련 문제