首页 > 解决方案 > Angular 6 Observable 链接和错误处理

问题描述

我通过 observable 获取参数,如果它是正确的枚举类型,那么我会获取数据。我没有使用快照来获取参数。这需要使用可观察的。

此外,页面上有一个刷新按钮,它直接调用第二个数据方法,因为我们将有正确的枚举可用于获取数据。

目前以下对我有用。

export class MaintainComponent implements OnInit, OnDestroy {
  grouptType: zGroupTypes;
  title: string = "";
  isError: boolean = false;
  errorMessage: string = "";
  groupList: Group[];

  //handles to destroy the observables manually 
  activatedRouteSubscription: Subscription; 
  groupSubscription: Subscription;

  constructor(private activatedRoute: ActivatedRoute, private router: Router, private dataService: DataService) { }

  ngOnInit() {
    this.title = "";
    this.isError = false;
    this.errorMessage = "";
    this.groupList = [];

    this.checkAndGetData();
  }

  ngOnDestroy() {
    this.activatedRouteSubscription.unsubscribe();
    this.groupSubscription.unsubscribe();
  }

  onRefresh() {
    this.getGroupInfo();
  }

  checkAndGetData() {

    this.activatedRouteSubscription = this.activatedRoute.params.subscribe(
      (params: Params) => {
        this.grouptType = <zGroupTypes>params['type'];
        if (this.grouptType && this.grouptType in zGroupTypes) {
          //good
          this.title = zGroupTypes[this.grouptType];
          //get the group info
          this.getGroupInfo();
        }
        else {
          //error - redirect to resource missing
          this.router.navigate(['resource-missing']);
        }
      }
    );
  }

  getGroupInfo() {
    this.groupList = [];
    this.isError = false;
    this.errorMessage = "";

    const params = new HttpParams().set('groupType', this.grouptType.toString());
    this.groupSubscription = this.dataService.pull<Group[]>(`${this.dataService.endPointGroup}/GetGroupByAttributeId`, params).subscribe(
      res => {
        //res is of type Group[]
        if (!res || res.length <= 0) {
          this.isError = true;
          this.errorMessage = "No Data Found";
        }
        else {
          this.groupList = res;
        }
      },
      error => {
        this.isError = true;
        this.errorMessage = "Error happened"; //console.log(error);
      }
    );
  }

}

我想重写它,这样我就不会在可观察对象中使用可观察对象。经过一番阅读,我必须使用 mergeMap 但是如何

  1. 处理由我的两个函数处理的错误。
  2. 刷新时仅拉出 groupInfo,因为我不需要再次获取 groupId。它将填充页面加载。

我在网上找到了一个例子来做链接,看起来像

export class AppComponent {
  homeworld: Observable<{}>;
  constructor(private http: HttpClient) { }

  ngOnInit() {
    this.homeworld = this.http.get('/api/people/1').pipe(
      mergeMap(character => this.http.get(character.homeworld))
    );
  }
}

但这并没有显示如何处理错误。

我开始了一些类似跟随的事情,但我有点迷失了,因为我对 Angular 还比较陌生,操作员仍然不是我的强项。

  getData() {
    let singleCall = this.activatedRoute.params.pipe(
      map(params => {
        this.grouptType = <zGroupTypes>params['type'];
      }),
      filter(() => this.grouptType && this.grouptType in zGroupTypes),
      mergeMap(() => {
        const paramToPass = new HttpParams().set('groupType', this.grouptType.toString());
        this.dataService.pull<Group[]>(`${this.dataService.endPointGroup}/GetGroupByAttributeId`, paramToPass)
        .... how to proceed here
      })
    );
  }

或者可以肯定地说我原来的方法仍然是处理这种情况的正确方法。

标签: observableangular6

解决方案


map函数中,您必须返回新值。不要在其中分配副作用。此外,在这种情况下,您应该使用switchMap而不是mergeMap

getData() {
  let singleCall = this.activatedRoute.params.pipe(
    map(params => params.type),
    tap((groupType) => this.groupType = groupType),
    filter((groupType) => groupType && groupType in zGroupTypes),
    switchMap(() => {
      const paramToPass = new HttpParams().set('groupType', this.grouptType.toString());
      return this.dataService.pull<Group[]>(`${this.dataService.endPointGroup}/GetGroupByAttributeId`, paramToPass)
    })
  );
}

编辑:如果你想切换大小写groupType,你可以扩展到 2Observable

const param$ = this.activatedRoute.params.pipe(
  map(params => params.type),
  tap((groupType) => this.groupType = groupType),
);

param$.pipe(
  filter((groupType) => !(groupType && groupType in zGroupTypes)),
).subscribe(() => {
  console.error("Failed")
});

param$.pipe(
  filter((groupType) => groupType && groupType in zGroupTypes),
  switchMap(() => {
    const paramToPass = new HttpParams().set('groupType', this.grouptType.toString());
    return this.dataService.pull<Group[]>(`${this.dataService.endPointGroup}/GetGroupByAttributeId`, paramToPass)
  })
).subscribe((results) => {
 // to do
});

推荐阅读