2017-12-08 21 views
0

私はデータベースからデータを取得したい。私はangular.ioのウェブページの例に従っていますが、私が正しいことをしているかどうかはわかりません。角2正確な方法サーバーからデータを取得する

私はフォームを持ち、ユーザーが郵便番号フィールドを埋めると、データベースを呼び出して都市の名前を取得します。存在しない場合は、ユーザーに記入してください。 私の問題は、正しく行う方法がわかりません。

私のサービスで。

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

、これが私の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); 
}; 

これはあなたのコンポーネントにObservableを返します。 ts

あなたのcomponent.tsのコードは今すぐに動作します

+0

ありがとうございました。出来た。 – dmance

+0

問題はありません、角をお楽しみください! –

+0

cityFromDb.nameの代わりにcityFromDb.city.nameのようにプロパティにアクセスするのは正しいですか? – dmance

関連する問題