MEANスタックにてWebサービスを開発しています。
MongoDB, Express, Nodeを用いてデータベース上からデータを取得するAPIを作成しました。
これを用いて、Angularでページを作成したいのですが、APIを呼ぶタイミングや方法で困っています。
仮に以下のようなAPIがあるとします。
APIの仕様(例)
GET /api/list1
response
1{ 2 success: true, 3 data: ['AAA', 'BBB', 'CCC', 'DDD', 'EEE'] 4}
GET /api/list2
response
1{ 2 success: true, 3 data: ['あああ', 'いいい', 'ううう', 'えええ', 'おおお'] 4}
これを行うために以下のようなコードを書きました。
Angularのコード
api.service.ts
typescript
1import { HttpClient} from '@angular/common/http'; 2import { Observable } from 'rxjs/Observable'; 3 4export class ApiService { 5 constructor(private http: HttpClient) {} 6 get_list1() { 7 return this.http.get('/api/list1').catch(error => { 8 // 9 return Observable.throw(error); 10 }).sharedReplay(); 11 } 12 get_list2() { 13 return this.http.get('/api/list2').catch(error => { 14 // 15 return Observable.throw(error); 16 }).sharedReplay(); 17 } 18}
app.component.html
html
1<select id="list1"> 2 <option *ngFor="let item of list1" ![イメージ説明](051dedbbc6d82d0a26a8ec265eecb428.png)"{{item}}">{{item}}</option> 3</select> 4<select id="list2"> 5 <option *ngFor="let item of list2" value="{{item}}">{{item}}</option> 6</select>
app.component.ts
typescript
1import { Component } from '@angular/core'; 2import { ApiService } from './services/api.service'; 3 4@Component({ 5 selector: 'app-root', 6 templateUrl: './app.component.html', 7 styleUrls: ['./app.component.css'] 8}) 9export class AppComponent { 10 list1: string[]; 11 list2: string[]; 12 constructor(private apiService: ApiService) {} 13 ngOnInit() { 14 this.apiSerivce.getList1().subscribe((res :{success: true, data: string[]}) => { 15 if(data.success) { 16 this.list1 = res.data; 17 }else { 18 console.log('get list1 error'); 19 } 20 }); 21 this.apiSerivce.getList2().subscribe((res :{success: true, data: string[]}) => { 22 if(data.success) { 23 this.list2 = res.data; 24 }else { 25 console.log('get list2 error'); 26 } 27 }); 28 } 29}
APIを呼ぶタイミング(ngOnInitで呼んでも構わないのかどうか)と、
このように、並列?にAPIを呼ぶ方法があまり良いとは思えないので、
複数のAPIを呼ぶ際はどのようにすればよいか、ご教授ください。
よろしくお願いいたします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/09/03 03:46
2018/09/03 06:29