📝

AngularでAPIのレスポンス値を画面に表示する方法【NgRx編】

に公開

1.APIのレスポンス値をstore経由で取得

component.ts
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { Store, select } from '@ngrx/store';
import { AppState } from '../store/app.state';
import { selectApiResponse } from '../store/selectors';

@Component({
  selector: 'app-sample',
  templateUrl: './sample.component.html',
})
export class SampleComponent {
  // storeからAPIレスポンスを取得(Observable型)
  readonly apiRes$: Observable<{ hoge: string }> = this.store.pipe(
    select(apiResponse)
  );

  constructor(private store: Store<AppState>) {}
}
  • apiResponseを定義
selectors.ts
export const apiResponse = (state: AppState) => state.apiResponse;

2.APIのレスポンス値をテンプレートに表示

component.html
<!-- テンプレート側でngIf+asyncパイプを使用して値を表示 -->
<div *ngIf="apiRes$ | async as res">
 <p>{{ res.hoge }}</p>
</div>

Discussion