私はAngular 2を初めて使用しています。エラー2のAPIサービスでエラーUIメッセージが表示される
サーバーからデータを取得し、コンポーネントに表示する必要があります。サーバーは、いくつかのAPIメソッドを持っているので、私はこのようになりますapi.service.ts
を作成しました:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
const protocol = 'http';
const domain = 'mydomain.ng';
const port = ':4200';
@Injectable()
export class ApiService {
constructor(private http: HttpClient) { }
buildQuery(apiMethod: string) {
return `${protocol}://${domain}${port}/${apiMethod}`;
}
get(apiMethod: string): Observable<Response> {
const query = this.buildQuery(apiMethod);
return this.http.get<Response>(query)
.map(
resp => {
if (resp.ok) {
return resp;
} else { // Server returned an error
// here I need to show UI error in the component
}
}
)
.catch(// Error is on the client side
err => {
// here I need to show UI error in the component
}
);
}
getGeneralReport(): Observable<Response> {
return this.get('generalReport');
}
}
サーバーAPIは、メソッドの多くを持っているので、get()
方法は、実際に実行するように設計されていますよくある間違いをリクエストして処理します。次に、getGeneralReport()
のようなメソッドを使用します。このメソッドは、使用するAPIメソッドを指定するパラメータでgetメソッドを呼び出します。
import { Component, OnInit } from '@angular/core';
import { ApiService } from '../../shared/api/api.service';
@Component({
selector: 'app-general',
templateUrl: './general.component.html',
styleUrls: ['./general.component.scss']
})
export class GeneralComponent implements OnInit {
generalInfo: Response;
constructor(private apiService: ApiService) { }
ngOnInit() {
this.apiService.getGeneralReport().subscribe(
data => {
this.generalInfo = data;
// Display the received data
}
);
}
}
api.service
を使用しますgeneral.component
ようなより多くの部品があります:
また、私はapi.service
が注入されgeneral.component.ts
と呼ばれるコンポーネントを持っています。今私は、api.service
にエラーが発生した場合は、api.service
を使用するすべてのコンポーネントでUIウィンドウをポップアップする必要があるために立ち往生しています。それは可能かどうか、私はいくつかの異なるアプローチを使用する必要がありますか?
this.apiService.getGeneralReport().subscribe(
data => {
this.generalInfo = data;
// Display the received data
},
err => {
// yourPopupmethod(err)
}
);
とサービススローエラーで:
答えをありがとう。しかし、私はapi.serviceを利用するコンポーネントをたくさん用意しているので、コードの重複を避けるために、すべてのエラー処理コードをサービスに配置する必要があります。これは可能ですか? –
はい、今編集します – komron
ところで 'if(resp.ok){ return resp; } else {} 'サーバーがエラーを返したかどうかをチェックする方法が不正です – komron