2017-12-08 1 views
0

데이터베이스에서 데이터를 가져오고 싶습니다. angular.io 웹 페이지의 예제를 따르고 있지만 올바르게 작동하는지 잘 모르겠습니다.각도 2 서버에서 데이터를 가져 오는 올바른 방법

양식이 있고 사용자가 우편 번호 필드를 채울 때 데이터베이스를 호출하여 도시 이름을 가져 오거나 존재하지 않는 경우 사용자에게 채울 것을 요청합니다. 제 문제는 올바르게 수행하는 방법을 모르겠습니다.

내 서비스. 내 component.js

checkCp(): void { 
    this.modal.header = 'Searching city'; 
    this.modal.text = 'Please wait'; 
    this.openWaitModal(); 
    this.studentService.checkCp(this.city) 
    .subscribe(cityFromDb => { 
     if(cityFromDb ===null) { 
     this.closeWaitModal(); 
     this.modal.header = 'Postal code not found'; 
     this.modal.text = 'Insert the name of the city'; 
     this.modal.no = 'Cancel'; 
     this.modal.yes = 'Insert'; 
     this.modal.action = 'newCity'; 
     this.modal.enableInput = true; 
     this.openModal(); 
     }else{   
     this.closeWaitModal();   
     this.city = cityFromDb.city; // I can't access cityFromDb.name 
            // i access via cityFromDb.city.name 
    } 
    }, err => { 
    this.errorHandler(err); 
    }) 
} 

답변

3

다음과 같이 당신은 당신의 서비스를 호출 할에

checkCp(city: City): Observable<any> { 
    return this.http.get<any>(this.backendUrl + 'api/city/' + city.cp).pipe(
    tap(city => console.log("fetched"))  
); 
} 

이는이 :

checkCp(city: City): Observable<any> { 
    return this.http.get<any>(this.backendUrl + 'api/city/' + city.cp); 
}; 

이 구성 요소에 Observable를 반환합니다. ts

귀하의 component.ts에있는 코드가 지금 작동합니다.

+0

고마워요. 그것은 효과가 있었다. – dmance

+0

문제 없습니다. 각도를 즐기세요! –

+0

cityFromDb.name 대신 cityFromDb.city.name에이 방식으로 속성에 액세스하는 것이 맞습니까? – dmance

관련 문제