秋田angular selectQuery catch 404

akita angular selectQuery catch 404

我正在研究 NgRx 的替代品。到目前为止,秋田犬是一个不错的选择,但我正在为错误管理而苦苦挣扎。有时我希望错误是应用程序范围内的,有时我希望它由组件管理。在下面的示例中,我启动了一个 404 错误,我希望我的组件知道这一点并采取相应的行动,但我不知道该怎么做。你能帮忙吗?

DummyService(秋田):

 get(id: number) {
    this.dummyService.loadByID(id).then((dummy: Dummy) => {
      this.akitaDummyStore.setDummy(dummy);
    })/*.catch((err) => {
      alert(err);
      Here it's working I go inside catch but I don't want it here I want the catch in the component
    })*/;
  }

组件:

  constructor(
    private akitaDummyQuery: AkitaDummyQuery,
    private akitaDummyService: AkitaDummyService
  ) {
  }

  ngOnInit() {

    this.akitaDummyQuery.selectEntity(666).subscribe(
      akDummy => {
        if (!akDummy) {
          this.akitaDummyService.get(666);
          return;
        }
        this.dummy= Dummy.parse(akDummy.result);
      },
      error => {
        //here I would like to catch the error in the component in order to display a component level error message. 
        alert(error);
      }
    );
  }

}

我可以这样处理错误:

this.akitaDummyQuery.selectEntity(id).subscribe(
  akDummy => {
    if (!akDummy) {
      this.akitaDummyService.get(id).catch(err => {
        if (err.statusText === 'Not Found') {

        }
      });
      return;
    }
    this.dummy = Dummy.parse(akDummy.result);
  });

但是当我这样做时,akita redux 对象保持在 "loading" state = true

感谢@NetanelBasal 我能够解决我的问题,我做错了所有事情:

秋田服务

export class AkitaDummyService {
  constructor(private akitaDummyStore: AkitaDummyStore, private dummyService: DummyService) {
  }
  get(id: number) {
    return this.dummyService.get(id).pipe(tap((dummy) => this.akitaDummyStore.add(createAkitaDummy(dummy.data))));
  }
}

秋田犬查询

export class AkitaDummyQuery extends QueryEntity<AkitaDummyState, AkitaDummy> {

  constructor(protected store: AkitaDummyStore) {
    super(store);
  }

  selectEntity<R>(id: getIDType<AkitaDummyState>): Observable<Dummy | any> {
    return super.selectEntity(id).pipe(filter(dummy => !!dummy), map((dummy: AkitaDummy) => Dummy.parse(dummy)));
  }

}

组件

export class PageDummyComponent implements OnInit {
  dummy: Dummy;

  constructor(
    private akitaDummyQuery: AkitaDummyQuery,
    private akitaDummyService: AkitaDummyService
  ) {
  }

  ngOnInit() {
    this.loadDummy(5);
  }


  loadDummy(id) {
    if (!this.akitaDummyQuery.hasEntity(id)) {
      this.akitaDummyService.get(id).subscribe({
        error: (err) => {
          // when 404 do something

        }
      });
    }
    this.akitaDummyQuery.selectEntity(id).subscribe(dummy => this.dummy = dummy);
  }
}