국가별로 도시를 검색하고 싶습니다.각도 4 관측 가능한 여러 번 전화 서비스
나는이 두 개의 서로 다른 공유 구성 요소 : 국가 검색을위한 첫 번째 일이 방출 선택한 국가 ID를 다음 두 번째 구성 요소는이 나라 ID를 얻을 에 서비스를 전달하지만이 도시를 필터링하고 데이터베이스에있는 모든 도시를 반환하지 않습니다 공유 .
내가 쉬는 상태에서 디버그 할 때 : countryId를 전달하지 않으면 모든 도시를 반환하고 모든 도시를 반환하지만 countryId를 전달합니다. 잠시 후 countryId 값이 변경되면 (null 또는 0) 전체 도시가 반환됩니다. 이 scenerio에는 어떤 문제가 있습니다. 감사합니다. .
//Component
export class CitySharedComponent implements OnInit {
cities = new Array<City>();
searchTerm$ = new Subject<string>();
public selectedCountryId = new BehaviorSubject(0);
@Input() countryId: any;
constructor(private service: CityService) { }
ngOnInit() {
this.service.search(this.searchTerm$, this.selectedCountryId.getValue(), 1)
.subscribe(results => {
this.cities = results;
});
}
onKeyup(searchText: string) {
if (searchText != null)
this.searchTerm$.next(searchText);
}
ngOnChanges(changes: { [propName: string]: SimpleChange }) {
if (changes['countryId']) {
if (changes['countryId'].currentValue == null || changes['countryId'].currentValue == undefined)
changes['countryId'].currentValue = 0;
this.cities = null;
this.selectedCountryId.next(changes['countryId'].currentValue);
}
}
}
//Service
search(terms: Observable<string>, countryId, lang): Observable<City[]> {
var headers = new Headers();
headers.append('Authorization', `bearer ${this.auth_key}`);
headers.append('Content-Type', 'application/json');
return terms
.distinctUntilChanged()
.switchMap(term => this.http.get(`${this.url}/search/${countryId}/${lang}/${term}`, { headers })
.map(data => data.json())
)
}
먼저 quickrespone에게 감사드립니다. 아래 코드를 변경했지만 작동하지 않습니다. DB에있는 모든 도시를 반환합니다. ngOnInit() { this.selectedCountryId.subscribe (data => { this.search (data); }); } 검색 (ID : 숫자) { this.service.search (this.searchTerm $으로, ID 1) .subscribe (결과 => { = this.cities의 결과, 입력 코드 'here' }) ; } 그러나 하드 코딩 된 값을 검색 (예 : countryId = 25)으로 보내면 예상대로 작동합니다. –
@muratkurtun, 나는 나의 대답을 업데이트했다. 원래 전화에서 답변을하고 있었는데 코드를 편집하는 것이 매우 불편했습니다 :) –
감사합니다. 예상대로 작동합니다. 나는 너의 대답을 받아 들였다. –