有没有更好的办法

时间:2018-02-28 13:05:11

标签: angular rxjs

我使用有状态服务来提问。如果服务本地状态中存在问题,则返回它们,否则它将从http调用api请求它们并存储它们。

此服务方法返回Observable of Question []。我的容器将observable存储在变量中,并使用异步管道将其传递给表示组件。

我成功编写了服务功能,但我不确定这是最好的方法。

请告诉我是否有更好或更优雅的做法?

以下是代码:

question.api.ts

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))
        )
      )
    );
  }
}

问题-page.component.ts

@Component()
export class QuestionsPageComponent implements OnInit {
  public questions$: Observable<Question[]>;

  constructor(
    private _api: QuestionApi
  ) {}

  ngOnInit() {
    this.questions$ = this._api.getQuestions();
  }

问题-page.component

<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>

1 个答案:

答案 0 :(得分:0)

首先,创建一个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