[英]Is there a better way
我正在使用全狀態服務來提問。 如果問題在服務本地狀態下存在,則將其返回,否則它將通過對api的http調用請求它們並將其存儲。
此服務方法返回一個Observable of Question []。 我的容器將observable存儲在變量中,然后使用異步管道將其傳遞給表示組件。
我成功編寫了服務函數,但是我不確定這是最好的方法。
您能告訴我是否有更好或更優雅的方法?
這是代碼:
問題庫
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
import { map, switchMap, take } from 'rxjs/operators';
import { Question } from './models/question.model';
@Injectable()
export class QuestionApi {
static readonly BASE_PATH = 'http://myapi.io';
private _questionsSource = new BehaviorSubject<Question[]>(null);
constructor(
private http: HttpClient
) {}
public getQuestions(): Observable<Question[]> {
return this._questionsSource.asObservable().pipe(
switchMap(val => val ?
this._questionsSource.asObservable() :
this.http.get<Question[]>(`${QuestionApi.BASE_PATH}/question`).pipe(
map(data => this._questionsSource.next(data))
)
)
);
}
}
Questions-page.component.ts
@Component()
export class QuestionsPageComponent implements OnInit {
public questions$: Observable<Question[]>;
constructor(
private _api: QuestionApi
) {}
ngOnInit() {
this.questions$ = this._api.getQuestions();
}
問題頁面組件
<ng-container *ngIf="(questions$ | async) as questions; else loadingQuestions">
<app-questions [questions]="questions"></app-questions>
</ng-container>
<ng-template #loadingQuestions>
<p class="text-center">Loading questions</p>
</ng-template>
首先,創建一個QuestionsService來執行您的http調用。
其次,無需創建BehaviorSubject,只需返回您的Observables即可:
...
questions = undefined;
public getQuestions(): Observable<Question[]> {
return questions ? Observable.of(questions) :
this._questionsService.getQuestions()
.pipe(tap(questions => this.questions = questions));
}
...
如果您正在尋找一種更優雅的方法,那么您可能正在尋找@ ngrx / store 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.